Found this today while playing around, thought people might enjoy this riddle.
$> echo test.c
typedef int foo;
int main()
{
foo foo = 1;
return (foo) +0;
}
$> gcc -Wall -o test test.c && ./test && echo $?
What does this print?
- 0
- 1
- Some compilation warnings, then 0.
- Some compilation warnings, then 1.
- It doesn’t compile.
I’ll put an answer in the comments.
8 comments ↓
The answer is (2) – it successfully compiles and then returns 1.
The reason is that the local definition of foo shadows the global typedef once it is declared, so (foo) evaluates to (1) and not to an (int) cast.
Compiling with -Wshadow (which is not included in -Wall) would cause a warning about shadowing.
Moving the declaration of the variable out of main() and into the global scope would cause compilation to fail.
I think you meant “cat test.c”, not “echo test.c”
`+0` gave it away for me.
`return (foo) -1;` might better fool readers.
Since ./test returns 1, the && doesn’t happen and nothing is printed :-)
I guessed (3) — but no!
Actually for me it does not print anything. This is probably because ./test ends with exit code ‘1’.
Changing the line like this, prints ‘1’:
$ gcc -Wall -o test test.c && ./test ; echo $?
I confirm -W shadow behaviour.
6) It doesn’t print anything.
As && only executes the right-hand command after successful execution of the left-hand command and ./test exits with exit code 1, echo $? will not be executed ;-)
The answer is None of the above. It doesn’t print anything at all. The exit code of ./test is non-zero, so because of the && following it the echo command doesn’t get executed.