Jump to content

Beginner int main?

- - - - -

  • Please log in to reply
5 replies to this topic

#1
ShaunM

ShaunM

    Newbie

  • Members
  • Pip
  • 4 posts
What would be the difference from int main() and int main(void) ?
Are both of them really a void? Plus if you are using int or char in your program
wouldn't be better to have int main(int, char)

Thanks

Edited by ShaunM, 02 January 2012 - 05:37 PM.


#2
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
The standard declaration is

int main(int argc, char **argv)

{

\\Some code...

}

the argc and argv are used for getting arguments from the command line: argc has the count of arguments and **argv is an array of strings, each string an argument. If you don't plan to use command line arguments you can leave out the argc and argv and get int main().

I'd think that int main(void) is the same but I'm also not sure. I don't quite understand your last question though.
Latinamne loqueris?

#3
ShaunM

ShaunM

    Newbie

  • Members
  • Pip
  • 4 posts
mebob,

Ok, I understand what you are talking about. Your response answered my last question anyway. Can you please give me an example of what you mean as to using command line arguments. I haven't got that far yet as I have only used int main().

#4
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
Here is an extremely simple example of what you can do:

#include <stdio.h>


int main(int argc, char **argv)

{

    printf("%s", argv[0]);

    return 0;

}

This would simply print out the name of your program.

When the OS passes the arguments from the shell/command line, the first one it passes is the name of the program being called. Here, I simply print out the string pointed to by argv[0], which would be the first string passed to main. For going further, you'd want to check argc to get how many arguments are being passed (each one is a single string), then access your arguments through argv. Here's an example that would print out all the arguments passed to the program:

#include <stdio.h>


int main(int argc, char **argv)

{

    int i;


    for(i = 0; i < argc; i++)

    {

        printf("%s", argv[i]);

    }


    return 0;

}

I hope this helps you understand
Latinamne loqueris?

#5
ShaunM

ShaunM

    Newbie

  • Members
  • Pip
  • 4 posts
Excellent I understand now. I was looking online and was getting confused but this helped. Thanks so much

#6
ShaunM

ShaunM

    Newbie

  • Members
  • Pip
  • 4 posts
Yes it does. I was getting confused at other information on line but this cleared it up with the help of this The GNU C Programming Tutorial Thanks




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users