2 ms·
Normally, yes. But main() is special and implicitly returns 0, for whatever reason.
by TazeTSchnitzel 9y ago
Normally, yes. But main() is special and implicitly returns 0, for whatever reason.
- user5994461 9y agoAbsolutely not. You can look at a crashing programs and see the return code is a random value. You can also make a program that doesn't return anything and see that it's also a random value, though some compilers on some platforms might initialize that to zero.
- TazeTSchnitzel 9y agoNo, it's literally special-cased in the C standard.
- pjc50 9y agoSomeone should tell the gcc maintainers then. int main() { int a = 12; } $ gcc maintest.c $ ./a.out $ echo $? 148
- TazeTSchnitzel 9y ago$ cat test.c int main(void) {int a = 12;} $ gcc-6 test.c -o test --std=c89; ./test; echo $? 162 $ gcc-6 test.c -o test --std=c99; ./test; echo $? 0 Must be a C99 thing.
- albinofrenchy 9y agoThis isn't that conclusive of a test -- uninitialized memory is 0 relatively often.
- clarry 9y agohttps://github.com/gcc-mirror/gcc/blob/4bec7283cda24b180ea7a01ae62214058a8e0020/gcc/c/c-decl.c#L9275 https://github.com/gcc-mirror/gcc/blob/4bec7283cda24b180ea7a...
- pjscott 9y agoOkay, that is conclusive. (And I'm pleasantly surprised by how readable GCC's source code is.)
- kaushiks 9y agoThis has nothing to do with memory. The x86_64 ABI returns values from functions in the RAX register.
- albinofrenchy 9y agoSure; same point applies though -- just because 0 happens to be in RAX doesn't mean it's defined behavior.
- user5994461 9y agoJust tested on the MSVC compiler I have at hands. The standard is not respected.
- detaro 9y agoMSVC doesn't claim to implement C99, where this rule was added, so it kind of makes sense that it doesn't happen. (generally, if they added C99-stuff then only where it was required for C++)
- user5994461 9y agoint main(void) { __asm { mov eax, 123 } } // visual studio command line // cl testc.c // cl testcpp.cpp // testc.exe // echo C %errorlevel% // testcpp.exe // echo CPP %errorlevel% Indeed. It's a C99 thing. For those not familiar with MSVC. The C compiler is not C99 compliant and the C++ compiler is.
- 1_2__4 9y agoI love C but this whole thread highlights a lot of the criticism of it. Everyone's right based on some standard or switch, and everyone's wrong for the same reason.
- jstimpfle 9y agoThis is not specific to C, but common to all evolving standards. If you want portable code just drive on the middle of the road. Often this is as easy as coding to an older standard, like C89 with a few selected features from later standards, and adding some compatibility features / problem detection in the build system. And don't rely on features that are difficult to explain and/or add only questionable value. Just return 0 from main, it's the obvious simple thing to do.