Take the 2-minute tour ×

Example code:

#include <iostream>

int main()
    if(int a = std::cin.get() && a == 'a')


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?

share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

The and operator && has higher precedence than the assignment operator =. So in other words, your statement is being executed like this:

if (int a = (std::cin.get() && a == 'a'))

You really want to use explicit parentheses:

int a;
if ((a = std::cin.get()) && a == 'a')

Even better, write clear code:

int a = std::cin.get();
if (a == 'a')


share|improve this answer
Thanks, I understand now. –  Jesse Good May 22 '12 at 21:35
And, as long as you have to do it in two separate statements, you may as well do the initialization with the declaration and simplify the conditional: int a = std::cin.get(); if (a == 'a'). –  Rob Kennedy May 22 '12 at 21:38
@RobKennedy: Yes, I've always avoided issues like this by breaking the statements up, but I just wanted a good understanding. –  Jesse Good May 22 '12 at 21:42
@RobKennedy Very true; I was tempted to put that, but I wanted to get my answer out quickly. :-) Editing shortly. –  Platinum Azure May 22 '12 at 21:42
add comment

The expression gets evaluated just as if it was its own statement. Like this:


So it's equivalent to initialize a variable a with the result from std::cin.get() AND-ed with the comparison between an uninitialized variable and the literal char 'a'.

share|improve this answer
add comment

You are using the variable to initialize itself. First the memory is allocated then whatever was in that memory is compared to 'a' and the result used to initialize the variable.

share|improve this answer
add comment

Your Answer


