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.