Why compilation still work when inverting the main function argument position

StackOverflow https://stackoverflow.com/questions/19608230

  •  01-07-2022
  •  | 
  •  

문제

Why my C program doesn't work when I declare the main function like this (I inverted the arguments position) :

int main(char * argv, int argc){
}

I compiled it without problem but I got errors when I run it.

Thanks.

도움이 되었습니까?

해결책

Due to the incorrect main() signature, this is not a valid C program.

Try enabling compiler warnings. My compiler tells me about the problem:

$ gcc -Wall test.c 
test.c:1:5: warning: first argument of 'main' should be 'int' [-Wmain]
test.c:1:5: warning: second argument of 'main' should be 'char **' [-Wmain]

See What are the valid signatures for C's main() function?

다른 팁

Unlike in C++, functions in C are solely identified by their names, not their arguments. E.g. linker will be pretty happy when it sees a 'main' function.

Nevertheless, there are certain assumptions how main() is called by the operating system resp. the runtime environment. When your parameters are wrong, your program will see unexpected values and might crash.

And btw, you probably will see errors or warnings when you enable diagnostics (e.g. '-Wall -W') when building the program.

This is an incorrect main() signature. You may check the main function.

The parameters argc, argument count, and argv, argument vector,1 respectively give the number and values of the program's command-line arguments. The names of argc and argv may be any valid identifier in C, but it is common convention to use these names.

Also check What should main() return in C and C++?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top