0

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

int main()
{
    return 1;
}
2
  • 1
    How do you invoke the program and test its return status from your shell?
    – Kusalananda
    Apr 25, 2019 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, 2019 at 8:09

2 Answers 2

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.

0

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.

4
  • I compiled the same code with 'gcc'. Still get the same result. Apr 25, 2019 at 6:28
  • what distribution are you using? what terminal? (bash?). $? is a shell built in variable. Apr 25, 2019 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? Apr 25, 2019 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. Apr 25, 2019 at 6:52

Not the answer you're looking for? Browse other questions tagged .