0

I have following code:

int X = 1;
if (int X = X)
{
    printf("%d\n", X);
    if (int X = X)
    {
       printf("%d\n", X);
    }
}

My expectation is X should be 1, 1. However, the output is:

1818935350
32767

Anyone know what's going on here? Compiled with clang-800.0.42.1

Edit: I tried the following code with a bit tweak, and now it behaves as I expected.

int X = 1;
if (int Y = X)
{
    printf("%d\n", Y);
    if (int Z = X)
    {
        printf("%d\n", Z);
    }
}

One guess is when you use variable on RHS of a declaration inside if statement, it might not refer to the variable with the same name declared at parent scope, instead it's referring to the variable that's being defined...

A.Stone
  • 137
  • 1
  • 9
  • get rid of the 'int' before the X in the if statement. Also if you want to make a comparison you need to use `==` not `=`. `=` sets the value of X. However, it's tough seeing what you're trying to accomplish here. Maybe give some desired input and output – bpgeck Nov 13 '16 at 04:44
  • 1
    @bpgeck That's not what I intend to do. I want to check the behaviour when you use declaration inside if statement. – A.Stone Nov 13 '16 at 04:46
  • @Avi Berger Yeah I know, but believe or not. I got a problem that's kind of similar to this. I need some macro that will be expanded to the if statements, and I want them to automatically refer to the one with the same name in parent scope ... Seems that's not possible. – A.Stone Nov 13 '16 at 05:08
  • See [Has C++ standard changed with respect to the use of indeterminate values and undefined behavior in C++14?](http://stackoverflow.com/q/23415661/1708801) for a more detailed explanation of the issue. – Shafik Yaghmour Nov 13 '16 at 05:58
  • @ShafikYaghmour Nice reference, didn't know that before :) – A.Stone Nov 13 '16 at 15:25

3 Answers3

4

When you say int X = X, both X's refer to the same int. That is, the one you are declaring right there in that line. So you are initializing X with itself, which is undefined behavior, since it was (of course) not already initialized. The X that you initialized with 1 is never printed in your code, since it is declared in a parent scope and shadowed by the ones in the inner scopes.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
0

In C, this if (int X = X) is plain wrong because the if statement expects a control expression - but NOT a declaration.

6.8.4.1 The if statement

The controlling expression of an if statement shall have scalar type.

I'm not sure about clang, but gcc gives this code an obvious error (not a warning) even without any compiler flag (ie without -Wall -Wextra)

error: expected expression before ‘int’

Community
  • 1
  • 1
artm
  • 17,291
  • 6
  • 38
  • 54
-1

Change all the ( Int X =X) to (X) It is creating new variables and possibly returning old data stored in that location.