0

For the following program, I get 0 for echo$? even though I expect 1.

int main()
{
    return 1;
}

closed as off-topic by Romeo Ninov, muru, Michael Homer, Jeff Schaller Apr 25 at 9:56

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Michael Homer, Jeff Schaller
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    How do you invoke the program and test its return status from your shell? – Kusalananda Apr 25 at 6:39
  • Buried in an answer comment is the important information that the questioner had not actually run the compiled program. – JdeBP Apr 25 at 8:09
1

if I compile your code using gnu g++ on my system: echo $? gives me 1. Do you have the same problem with a code in c, bash, python, ...? Also: be aware that $? is available only for the last command's return: the $? for echo $? is 0.

  • I compiled the same code with 'gcc'. Still get the same result. – Pradeep Sanjeewa Apr 25 at 6:28
  • what distribution are you using? what terminal? (bash?). $? is a shell built in variable. – Vincent Achard Apr 25 at 6:29
  • Also: are you: 1) compiling, obviously getting no error, 2)running the compiled binary, 3)running echo $? in that order, doing nothing in between, in particular between steps 2 and 3? – Vincent Achard Apr 25 at 6:39
  • 1
    Oh, you caught my mistake; silly mistake. I wasn't running the compiled binary and expected '1' for the compilation. Thanks a lot for your guide. – Pradeep Sanjeewa Apr 25 at 6:52
1

Your program works just as you expect it to:

$ cat prog.c
int main()
{
    return 1;
}
$ cc prog.c
$ ./a.out
$ echo $?
1

Note that if you do anything in-between running your program and outputting $?, the value of $? will be overwritten by the exit-status of the commands that you use. For example,

$ ./a.out
$ echo "I ran the program"
I ran the program
$ echo $?
0

The 0 here is the exit status of echo.

Not the answer you're looking for? Browse other questions tagged or ask your own question.