Example code:
#include <iostream>
int main()
{
if(int a = std::cin.get() && a == 'a')
{
std::cout << "True" << std::endl;
}
}
Question:
When I compile this code, visual studio gives me a nice warning: warning C4700: uninitialized local variable 'a' used. So I understand that a is uninitialized. However, I wanted to fully understand how the expression is evaluated. Is it the case that the if statement above is equivalent to if(int a && a == 'a') { a = std::cin.get(); }? Could someone explain exactly what happens?
The and operator
&&has higher precedence than the assignment operator=. So in other words, your statement is being executed like this:You really want to use explicit parentheses:
Even better, write clear code:
🙂