Knowledge of how to define functions at the right time

This is a "strange" question, as it bothers me. I am learning C, and I realized that I have a question not in my book C.

When starting a function, for example int main() or void name() , HOW I know what to put in brackets ... for example int main(int argc, char *argv[]) or just int main() .

This is a stupid question, but I would not know WHEN to use that when programming. Resources for online links will be helpful.

Thank you, and sorry for the stupidity.

+4
source share
3 answers

The variables that you pass to the function are its inputs or (sometimes) its outputs. For example, if you want to write a function that adds two integers and returns their sum, you can define

 int sum(int m, int n) { return m + n; } 

The main() function is a special case, since it works with command-line arguments that are provided to the program. In most languages, main() takes an array of strings with one word from the command line on each line. In C, it also accepts an integer that represents the number of words that were entered on the command line.

+5
source

In your specific question about main() you will need the arguments inside the parentheses when you want to access the command line arguments that were passed. Perhaps you can confuse different ways of declaring functions. As a novice C programmer, you should always use int func(int a, int b) , declaring your return type, function name, parameters, and parameter types on the same line. Do not let other syntaxes confuse you - most of them exist for historical reasons, and when you know enough to answer, you know why they are there, you will know enough to answer this question yourself :)

+4
source

Even if the signature is main(int argc, char *argv[]) , it is not uncommon to see int main() . This works because C is not particularly strict in verifying the signatures of external functions (however that may be: when you call an external function in C, you simply point to the function and argument list, there is no way it can really verify that you are using this function as it was originally defined.)

So this will work too:

 int main(int argc) { return 0; } 

Even this will be:

 int main(int argc, char *argv[], int foo) { return 0; } 

just don't expect the meaningful value to appear in foo .

+1
source

Source: https://habr.com/ru/post/1412441/


All Articles