2

I found out by accident that in C/C++ I can initialize a variable with itself:

#include <stdio.h>
static const int foo = foo;
int main() {
    int bar = bar;
    printf("%i, %i", foo, bar);
}

Depending on compiler version I get different results:

Those just print "0, 0" on my machine:

  • g++.exe (Rev1, Built by MSYS2 project) 5.3.0
  • g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
  • gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

This one gives an error:

  • gcc.exe (Rev1, Built by MSYS2 project) 5.3.0
    foo.c:2:28: error: initializer element is not constant
         static const int foo = foo;
                          ^

Why does this work and what would the expected behavior be?

rnstlr
  • 1,627
  • 14
  • 17
  • You probably had `-Wall -Werror` only for the last one. Show your options. – LogicStuff Feb 12 '16 at 12:20
  • @erip, I also agree with you. I also flagged your duplicate questions. By the way, this is also a duplicate of: [Does initialization entail lvalue-to-rvalue conversion? Is `int x = x;` UB?](http://stackoverflow.com/questions/14935722/does-initialization-entail-lvalue-to-rvalue-conversion-is-int-x-x-ub) – Box Box Box Box Feb 12 '16 at 12:22
  • @LogicStuff I compiled without any options. With Wall the other compilers show a warning for `int bar = bar` – rnstlr Feb 12 '16 at 12:28
  • Please choose one of C and C++ for your questions. – fuz Feb 12 '16 at 13:09
  • `int bar = bar;` is OK, but `int bar = bar + 1;` is not. This, because bar is uninitialized here. – Michi Feb 12 '16 at 15:31

0 Answers0