tags:

views:

256

answers:

3

This actually bugging me from quite sometime now.The question is like this : How to set the the exit status of a program to any value without explicitly using return/exit in gcc/g++ ? Let us consider this piece of code : (Takes input from stdin and print it to the stdout until a zero input 0 is encountered)

#include <stdio.h>

int main() {
  int n;
  while(scanf("%d",&n) && n>0 )
    printf("%d\n",n);
}

In my system (which is windows + mingw) it is returning 1,How to make it to return 0 or anything else implicitly without explicitly using exit/return ?

EDIT :

I modified the code a bit :

int f(int n) { 
  return (n>0);
}

int main(){
  int n;
  while(scanf("%d",&n)&&f(n))
    printf("%d\n",n);
}

It's now returning 0 implicitly,but I couldn't draw any firm conclusion from this.

A: 

The point is your program will eventually terminate - for example, the runtime will call ExitProcess() on Windows or an equivalent function on another OS. The primitive used to end the program will set the error code (exit status) that will override the code previously set by you directly.

Maybe there're some C++ runtime implementations that allow what you want, but overall the behavior is as I described above.

sharptooth
+2  A: 

In C++ and in C99, leaving main without executing exit() or return should be equivalent to return 0 (see 5.1.2.2.3 for C, 3.6.1/5 for C++), C89 leaved that undefined if I recall correctly.

AProgrammer
Yes,I am aware of this but still some GCC versions is behaving strange for some programs like the the one I showed above,
nthrgeek
Undefined is undefined... as the support for C99 by gcc is still incomplete, you probably tested version before and after that feature has been added.I would not be suprised that the result of main was the result of the last function called, if you don't do too many things after. That seems to explain the behaviour you observe in your edit.
AProgrammer
+1  A: 

I think your implementation is using the return value of the last function called inside main() -- not a behaviour you can depend on, of course. (And may change with compilation options, i.e. inlining)

(This is probably due to the value left in the EAX register, as has been mentioned in the comments.)

The best I can come up with:

static int program_exit_value;

void setExitValue(int value)
{
    program_exit_value = value;
}

int main(void)
{
    ...

    return program_exit_value;
}

Which uses a return statement but has the advantage that it is ANSI-compliant.

aib