1

here is my code in linux:

#include <stdio.h>
static int tt(void);
static int tt(void)
{
  return 1;
}
int main(int charc,char **charv)
{
  tt();
}

in the shell:

$./a.out
$echo %?
$1

Why i got the "1" as the result

dbush
  • 205,898
  • 23
  • 218
  • 273
ccw
  • 69
  • 7
  • @usr Nopes, it is not. – Sourav Ghosh Mar 23 '17 at 14:51
  • Not a dupe (of that question) @usr. The issue here is that the program returns a different exit status than the standard says it ought to do. – John Bollinger Mar 23 '17 at 14:51
  • 3
    It is. It's question of whether OP compiles in C99 (or later) or before - in that case, it's *undefined behaviour* which is what I suspect. It's basically not understanding what main returns/supposed to return and/or C99 vs. eariler. There are a lot of info covered in the linked question. Have you read them all and concluded it's not? – P.P Mar 23 '17 at 14:53
  • @usr Agreed, I'll close this as a duplicate. The accepted answer in the duplicate addresses the `return` from main() issue. – Lundin Mar 23 '17 at 15:29

1 Answers1

7

Returning from a non-void function without returning a value is undefined behavior. You can't depend on the result.

There is a special case for the main function starting with the C99 standard. If no value is returned from main, a return value of 0 is assumed. However, you appear to be compiling in C89 mode (which is the default for gcc) where this is not allowed.

If I compile this code as C89, I get a warning about not returning a value. To demonstrate undefined behavior, if I compile without optimizations the exit status is 1, but if I compile with -O3 the exit status is 96.

If I compile in C99 mode I get no warning and the exit status of the program is 0.

To compile in C99 mode, pass the flag -std=c99 to gcc.

dbush
  • 205,898
  • 23
  • 218
  • 273