Tuesday, 29 November 2011

Few things about MAIN() ( C/C++)

Few things about MAIN()

We all are aware of tis function,right? We all love this function coz its the entry point of our software.Actually before main() is entered preprocessor is run which processes everything defined/declared before entering main(),for eg: including header files,processing macros, etc.
By ISO standard main() should always return int.
You should always declare int main(), you can also use void but remember the standard is using "int main()".
It should return 0 on successful completion and 1 on unsuccessful completion.
Remember you can also return any other value like return 10, return 23 anything but remeber what the standard is.

Passing Arguments to main()---->

int main( int argc, char* argv[] )
this is the syntax for main(),expecting 2 arguments ARGC( ARGUMENT COUNT ) of type int and ARGV( ARGUMENT VECTOR ) of type char**.It can also be denoted as char*[].It means that it points to an array of char*.You can also declare like
int main( int argc, char** argv )
There are at least two arguments to main: argc and argv. The first of these is a count of the arguments supplied to the program and the second is an array of pointers to the strings which are those arguments—its type is (almost) ‘array of pointer to char’.
Now u run the programme and say "hey, Wait id dint paased any arguments"
REMEMBER: that u pass arguments through command line i.e dos in other wrds command prompt(CMD).For any1 who hasnt seen cmd type cmd in run(win + r).

When a program starts, the arguments to main will have been initialized to meet the following conditions:
1. argc is greater than zero.
2. argv[argc] is a null pointer.
3. argv[0] will be a string containing the program's name or a null string if that is not available. Remaining elements of argv represent the arguments supplied to the program. In cases where there is only support for single-case characters, the contents of these strings will be supplied to the program in lower-case.
Now wat u actually do with these arguments inside your programme depends on you.
The most imp thing to remember is that :
ARGC(ARGUMENT COUNT) tells us how many arguments are passed to your programme which are stored in ARGV( ARGUMENT VECTOR ).
Default value of ARGC is 1 because the first argument inside ARGV is the path of the exe file itself(m talkng abt windows, dnt knw bt linux :( ).

A sample programme:
#include <stdio.h>

int main(int argc, char **argv)
printf("%s\n", *argv++);
return 0;

But on visual studio 2005 the implementation is a little diff.
for eg: if you pass 2 arguments to the programme,then argv[2] will be the name of the programme and not argv[0].
rest is same.
Write code to actually get the first hand experience.

No comments:

Post a Comment