0

Is it possible to give arguments in main() function?

19th Jan 2017, 9:42 AM
Aakash Garg
Aakash Garg - avatar
6 ответов
+ 5
you can give arguments or switches to your program from the command line. int main(int argc, char* argv[]) {} is this what you mean?
19th Jan 2017, 9:59 AM
jay
jay - avatar
+ 3
As an addition to jay: int main(int argc, char* argv[]) where argc is an int which holds the number of arguments given and char* argv[] is an array of the given arguments as c-strings. You can address both of them in your code just as any other variable or array. Have in mind, that your program call (e.g. ./myExe) is an argument, too. so your program name is saved in argv[0]. If you don't know what I am speaking of, read about C-Strings and Arrays.
19th Jan 2017, 11:10 AM
Abraham Soeyler
Abraham Soeyler - avatar
+ 3
On Unix Systems, you can also have a third parameter, that holds your environment variables. The following code works on the SoloLearn Playground: #include <iostream> using namespace std; int main(int argc, char *argv[], char ** envp) { char** env; for (env = envp; *env != 0; env++) { char* tmpEnv = *env; cout << tmpEnv << '\n'; } return 0; } and it looks like a windows-machine, so the third parameter works on windows too ;)
19th Jan 2017, 1:48 PM
bem
bem - avatar
+ 2
if you are a beginner you will probably don't need to give any arguments to the main function. Learn to write code and understand how function calls work, then go back to this article (or just google what the main function actually is). You can create fully working programs without using the arguments of the main function, don't worry ;) To answer your question: -yes, you can add parameter to the main call. -your teacher probably meant, that you don't have to use them, so you just write main()
19th Jan 2017, 1:59 PM
Abraham Soeyler
Abraham Soeyler - avatar
+ 1
well, I'm sorry to say but I'm only a beginner and i have not understood any of the answers.I had asked the question only because my CS teacher said that there is no use of arguments in main() function.Btw,thank you guys for giving me your precious time.
19th Jan 2017, 1:51 PM
Aakash Garg
Aakash Garg - avatar
+ 1
thank you Abraham 😃
19th Jan 2017, 5:05 PM
Aakash Garg
Aakash Garg - avatar