I'm studying the Declarations in Conditions topics in C and faced the below problem.
#include <iostream>
int main() {
int x;
std::cin >> x;
if(int a = 4 && a != x) {
std::cout << "Bug fixed!" << std::endl;
}
}
I declared and then initialized the variable a
. In the The C Programming Language by Bjarne Stroustrup Ed.2011, it is said:
The scope of variable declared in if statement extends from its point of declaration to the end of the statement that the condition controls.
That's what I did, I declared and initialized the variable a
, but when I try to compare it against x
, compiler gives uninitialized local variable a used
error. Why, what's the problem?
I can do
int a = 4;
if (a != x)
// ...
but I would like to do it in one line if possible.
CodePudding user response:
In the expression inside the if
condition
int a = 4 && a != x
what the compiler actually sees is
int a = (4 && a != x)
where the value of a
is clearly being used before it's initialized (which is what the error is saying), and is not the intent of the code.
From C 17, you can use if-with-initializer syntax to achieve the effect you want
if (int a = 4; a != x)
// ...