Riddle me this

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?

  1. 0
  2. 1
  3. Some compilation warnings, then 0.
  4. Some compilation warnings, then 1.
  5. It doesn’t compile.

I’ll put an answer in the comments.

1 comment so far ↓

#1 Benjamin Otte on 10.17.19 at 22:56

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.