Single = in if condition

What happens if we use a single "=" in an if condition?

1
2
3
4
int a = 1, b = 2;

if (a = b)
    printf("Hello\n");

The a = b is just an assignment statement. It assigns the value of b to a.
But even assignment statements are expressions and therefore have a value.
The value is whatever was assigned to the left-hand side.
So a is assigned the value 2 and the assignment expression has the overall value of 2, which is not zero and so is interpretted in a boolean context as true. Hello.

However, if you need to do that I think it's better to be more explicit:
 
if ((a = b) != 0)

It makes it stand out more as an assignment plus a relational test.
The GNU compilers generate a warning if they see an assignment inside an if. You can suppress the warning by adding an extra set of parentheses, which the compiler interprets as "I really meant this."
1
2
if ( a = b)   // generate s a warning
if ((a = b)) // no warning. 
The other "single =" in condition:
1
2
3
4
5
Base* b1 = ...
if ( Derived* d = dynamic_cast<Derived*>(b1) )
{
  // use d
}

That is initialization, not assignment, but it still returns the (new) value of 'd' to be evaluated as predicate.

The GNU compilers generate a warning if they see an assignment inside an if. You can suppress the warning by adding an extra set of parentheses, which the compiler interprets as "I really meant this."
1
2
if ( a = b)   // generate s a warning
if ((a = b)) // no warning.  



That is not the default behavior in a just-installed gcc/g++ under a just installed cygwin.

What platform are you using?
That is not the default behavior in a just-installed gcc/g++ under a just installed cygwin.
Good point. I'm running cygwin with "-Wall" on the command line so I get all warnings.
"-Wall" does not give all warnings, not by a longshot. "-Wall -Wextra -pedantic" yields more, but even then there are probably some warnings that need explicit enable.
Last edited on
That's good to know. Thanks!
Topic archived. No new replies allowed.