parsing parameters to main function [duplicate] - c++

This question already has answers here:
What does int argc, char *argv[] mean?
(12 answers)
Closed 6 years ago.
I don't understand the following piece of code:
int main(int argc, char** argv)
{
// See if we've been given a seed to use (for testing purposes). When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.
unsigned int seed = 0;
for(int ii=1; ii<argc; ii++) {
if(strcmp(argv[ii++],"seed") == 0) {
seed = atoi(argv[ii]);
}
}
How can I pass a value to main function? I read a bit and found out that it is called parsing, could you please clarify what is it?
Thanks,

The parameters int argc and char** argv are automatically passed to main and are parsed from the command line used to invoke the program. They are, respective, the number of command line parameters including the program name itself and an array of pointers to C-style strings of these parameters. So if the following is used to invoke my_prog:
./my_prog file 10
main gets called with argc set to 3 and argv is a char* array of 3 pointers to "./my_prog", "file" and "10"
EDIT: thanks to #BasileStarynkevitch for pointing out on POSIX complaint systems argv will have an argc + 1 element of NULL to also indicate end of parameters.

Related

How to check if arguments were passed in C++

I've recently started learning C++ and I'm a bit confused about argv and argc. I am trying to determine if arguments were passed to a program by checking the size of argc, but no matter how many arguments (including none) I pass to the program the size of it is always 4.
Simple example:
int main(int argc, char** argv)
{
std::cout << sizeof(argc); //outputs 4 with 0 or any num of arguments
std::cout << sizeof(argv); //outputs 8 with 0 or any num of arguments
}
I found this same question asked before and I apologise for repeating it but the answers on those pages I found were contradictory to what's happening here.
So, why is argc always 4 and is there any other way to check if arguments were passed to main()?
If it's relevant I'm using g++ to compile.
sizeof(argc) will always be the same value. sizeof(variable_name) gives you the size that variable takes up in memory. If you want to know how many parameters were passed you need to evaluate what the variable contains. For instance
std::cout << argc - 1;
Will have it display how may parameters were passed. The - 1 is needed because the first parameter is the name of the program so we don't want count that in the parameter count.
I am trying to determine if arguments were passed to a program by checking the size of argc
argc is the number of arguments. The size of argc is the size of int object.
So, why is argc always 4
Because the size of int object is always 4 bytes on your system.
is there any other way to check if arguments were passed to main()?
You can check the value rather than the size of argc:
std::cout << argc;
Note that there is (typically) at least one argument to the program: The command that was used to execute it.
sizeof gives you, at compile time, the size of the enclosed type.
So sizeof(argc) is sizeof(int), and sizeof(argc) is sizeof(char**). I hope you appreciate this is therefore completely independent of the arguments passed!
Simply rely on what C++ gives you: argc is the number of arguments passed, including the program name. And the number of elements in argv is the same as argc, with an addional one which is set to nullptr.

int main(int argc,char* argv[]) why does argc gives 2 argument? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
If I understood correctly using of int main(int argc,char* argv[]) , whenever I've declared 4 integer argc must be 5. For example;
int main(int argc,char* argv[])
{
int portNb = 0;
int leftMotorHandle;
int rightMotorHandle;
int sensorHandle;
if (argc>=5)
{
portNb=atoi(argv[1]);
leftMotorHandle=atoi(argv[2]);
rightMotorHandle=atoi(argv[3]);
sensorHandle=atoi(argv[4]);
}
else
{
printf("Indicate following arguments: 'portNumber leftMotorHandle rightMotorHandle sensorHandle'!\n");
extApi_sleepMs(55000);
return 0;
}
But argc's value is 2 when i debugged the code. How can i be sure that argc has value of 5 ?
If I understood correctly using of 'int main(int argc,char* argv[])' , whenever I've declared 4 integer argc must be 5.
argc and argv have nothing to do with the number of variables you declare within your program. argc means the number of arguments you provide when you run it from the command line. argv is the array of char pointers that point to your arguments (including the name of your program itself).
Assume your program called proc. You would need to run it from command line as (or else you would need to find out from your IDE how to provide the command line arguments).
./proc 5 10 15 20
The numbers 5, 10, 15, 20 would be your argv[1] .. argv[4]
You should input not less than 4 arguments from the command line.
Separate the arguments by space.
Int argc is argument count, means how many arguments your are passing, including program name.
char pointer array represent arguments

How does main() handle a variable number of arguments without ellipses? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
How does the main() function handle a variable number of arguments without the use of ellipses (...)? For processing variable number of arguments, last argument to the function should be ... which is not the case with the main() function.
Basically, main() is special, and it has two standard-defined forms:
int main(int argc, char **argv)
int main(void)
The system may support other forms; it is common that the environment is also made available:
int main(int argc, char **argv, char **envp)
These forms are fixed. The only unusual thing is that a system must support either of the first two (and some systems support others as well).
The variable number of command line arguments is handled via an array of pointers to strings (that's argv above), unlike say execl() from POSIX.
See also:
How does the main() function in C work?
What should main() return in C and C++?
rahul manglani commented:
The two links you mentioned made it pretty clear. There are different possible approaches listed there, which of them is actually being used is not mentioned.
In a sense, it doesn't matter; the system simply has to work, and the people who produce 'the system' must make it work. You as the programmer using the system don't need to know how it works; you can simply assume that it does work.
Behind the scenes, what usually happens is that the 'start' function which calls main() does some fixup work (in the case of a C++ program in particular, a lot of fixup work — such as ensuring all the constructors that must be executed before main() starts are in fact executed), but ends with a fixed sequence such as:
exit(main(argc, argv, environ));
Note that environ is a global variable, extern char **environ; (which is unique among the global variables defined by POSIX in that no header declares it) and it contains the pointers to the environment variables. The 'start' code has to ensure that is set; it is trivial to pass environ as an argument to main(), therefore.
This calls main() with a fixed argument list and calls exit() if/when it returns. Indeed, Apple takes it a step further and passes a fourth argument to main(). If the called function was defined as int main(void) { … }, it simply ignores the arguments it was passed; if it was defined as int main(int argc, char **argv) { … }, it can access the command line arguments as usual; if it was defined as int main(int argc, char **argv, char **envp) { … }, then it can access the environment too.
Generally, the systems are set up so that extra arguments don't cause damage. This is a reason why C is unusual in its calling conventions and it's why the called function doesn't clean up the arguments pushed onto the stack — the called function doesn't know how many arguments were actually pushed onto the stack. It assumes that the ones it expects were provided and uses those without problems, but the calling code knows what it pushed so it can clean up properly. The biggest problems occur if the called function expects N arguments but the caller passes M arguments and M < N. (There are also issues of types pushed and the sizes of those types, etc, but that's a second-order problem.)
In C/C++ main takes 2 parameters, typically called argc, and argv. The argv parameter is an array of argc char arrays. Command line arguments are passed to the program in argv. There are variations on this theme with the exact number of parameters, but main's signature is generally
int main(int argc, char **argv);
I interpreted this question to mean: how is it possible that main can take either zero arguments or two arguments?
While the details are obviously implementation-dependent, on most implementations, the default C calling convention is that the caller cleans the stack. Therefore, the code that calls main is at perfect liberty to always push two arguments onto the stack (argc and argv), whatever the declaration of main might be. If main is declared with no arguments, then main simply won't access the values of the arguments it receives. After main returns, the calling code clears the stack.
It should be pointed out that main isn't even special in this sense. Try this:
int printf();
int main() { printf("Hello, world!\n"); }
The C compiler will happily allow you to call printf even though, lacking an #include <stdio.h> directive, it has no idea how many arguments printf actually wants. Presumably, the code that calls main is conceptually something like this:
int main(int argc, char** argv); /* declare "main" */
main(argc, argv); /* call "main" */
If the definition of main actually specifies zero parameters, this still works (although I believe it would technically be undefined behaviour if you actually did this).
In the case of C++, although the linkage of main is left unspecified by the standard, most implementations simply treat it as though it has C linkage, so the name is not mangled and everything above still applies.
It handles it by accepting an array and array length set as variables argc and argv
you may find more data here:
http://crasseux.com/books/ctutorial/argc-and-argv.html

How many parameters can be passed to main() [duplicate]

This question already has answers here:
Can the arguments of main's signature in C++ have the unsigned and const qualifiers? [duplicate]
(7 answers)
Closed 8 years ago.
Is there a limit for the number of parameters main can have?
Here is a sample code which runs perfectly … and I am not aware if it is allowed.
int main( char* argv[], int argc, int arv, bool test)
{
cout<<"Hello"<<endl;
}
Output:
Hello
I am using
gcc-4.1.2_20070115-0.32.53
gcc-c++-4.1.2_20070115-0.32.53
libgcc-4.1.2_20070115-0.32.53
gcc-objc-4.1.2_20070115-0.32.53
The C++ standard does not explicitly forbid these signatures, but it does not require them to work either. All it says is that the two following signatures must work on any compiler:
int main()
int main(int, char**)
And that the return type must be int.

Why does main have an int in front of it and why could my Professor be excluding it? [duplicate]

This question already has answers here:
What is the proper declaration of main in C++?
(5 answers)
Closed 9 years ago.
So in my professor's slides he simply gives examples like:
main()
{...
}
Right? But when I put this in visual studio it gives an error and it works when I put int in front of main.
Why would my professor not put int in front of main?
Can main be any other type of variable?
Also I see a lot of int main(void). Why is this necessary? Can anything else be put in as a parameter?
main returns int. In older versions of C you could leave out the int and the compiler would pretend that you had said int. In C++, if 'main' doesn't explicitly return a value, it magically returns 0. You can return three values from main: 0, EXIT_SUCCESS, and EXIT_FAILURE. 0 is equivalent to EXIT_SUCCESS. The two named values are defined in <stdlib.h> and if you're coding in C++ in <cstdlib>.
The void is a C-style declaration that a function takes no arguments. In C++ you don't need it; a function that has no arguments in its declaration takes no arguments.
In general, though, main takes two arguments:
int main(int argc, char *argv[])
Those are the command-line arguments. argc is the number of arguments, and argv is an array of pointers to C-style strings that hold the arguments. The first string (argv[0]) is the name of the program.
Because you are using either: C++ or C99 or C11.
C89 had an implicit int rule that mades main() equivalent to int main(). This does not exist in C++ and no longer exists since C99.
As you mentioned you are using Visual Studio and it does not support C99 and C11, you are probably compiling your program with the C++ compiler and not the C compiler.
The standard form of the main function, traditionally, is
int main(int argc, char **argv)
The int in the front means the main function returns an int, which is the exit code of main. The perimeter passed in by the operating system argc and argv are related to command-line arguments. argc is an int indicating the number of arguments passed in to the program, including the name of the program. And argv is pointed to the individual arguments. You can use argv[index] to access them. There are several handy libraries for parsing arguments, such as getopt.