-1

I think this question is not a duplicate of other questions on the site, because others don't give uses of this feature in C.

I am interested in knowing why this C program is not giving a compile time error. Also why is this statement valid. What are its uses?

int main(int argc, char const *argv[])
{
    int k = k;
    return 0;
}

There is no k in the global scope. It looks as if scope of k started just after the assignment operator. I am confused.

daltonfury42
  • 3,103
  • 2
  • 30
  • 47
  • Indeed, the scope of a declared name begins right after the end of declarator, that's at the `=` sign in your case. Even if there were a global `i`, that `i` would have been hidden by the newly-declared `i`. You can make some fishy but legal code, e. g.: `int f(int* p), i = f(&i);` – ach Feb 28 '16 at 17:38
  • In the world of programming, "it works/seem to work/once worked" is a very subtle statement. – user3528438 Feb 28 '16 at 17:38
  • RE: your edit—there *are* no uses, it is undefined behavior. – Cody Gray - on strike Feb 28 '16 at 18:16
  • @CodyGray Why not remove it it a language revision if it is undefined in all cases? – daltonfury42 Feb 28 '16 at 18:37
  • That is not how the C language works. It does not protect you from shooting yourself in the foot. How would it even be "removed"? It is not allowed now! – Cody Gray - on strike Feb 29 '16 at 05:39

1 Answers1

3

the int i = i; definition initializes the (left) i with the (uninitialized value of the right) i (the same variable).

It is certainly unspecified behavior, and probably is undefined behavior.

The implementation is certainly not expected to always detect undefined behavior (always detecting them reliably can be proved equivalent to the halting problem).

But you really should be very scared of undefined behavior. It is your duty to avoid it.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547