1

Are there any recommendations about writing constants on the left of comparison operator equal to == in If statement in C++ to avoid bug if assignment will be mistyped. Is it a good practice ? or this will reduce code readability and not recommended to do that, as there is a Compiler Warning (level 4) C4706 in case if assignment within conditional expression will be written.

const int maxValue = 15;

1)

if (currentValue == maxValue)
{
    // do something 
}

(

if operator equal to == will mistyped to assignment operator =, currentValue = maxValue the if will be always true as anything that isn’t zero is “true”

Or better to write

2)

if (maxValue == currentValue)
{
   // do something 
}
T M
  • 3,195
  • 2
  • 31
  • 52

0 Answers0