CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    May 2006
    Location
    Norway
    Posts
    1,709

    VC++ General: How to avoid making an assignment when the intention is a comparison?

    Q: VC++ General: How to avoid making an assignment when the intention is a comparison?

    A: Lets say you want to check whether an integer is equal to another integer. Then since you are in a hurry you write this code:

    Code:
    // x is an integer declared and initialized somewhere else
    if (x = 1)
    {
         //Do Something
    }
    else
    {
         //Do something else
    }
    This compiles just fine and you assume that this is working the way it should. Then while debugging your program you suddenly realize that the else part of the if-statement is never executed! Or at least you can hope you will discover it!

    In the above code the else statement will never execute! The reason is that you are reassigning the value 1 to x. In other words, your code could have been written like this:
    Code:
    if (1)
    and obviously this will never be 0!


    Q: How can I avoid these possible disastrous errors?

    A: There are two possible solutions to this question:

    1. The easiest approach is to make it a habbit to put the constant part of the expression on the left-hand-side:
      Code:
      // x is an integer declared and initialized somewhere else
      if (1 = x)
      {
           //Do Something
      }
      else
      {
           //Do something else
      }
      This code will not compile! If you had written this in the first place you had discovered the error during compilation! The reason this will not compile is that you can not reassing a constant value!

    2. You can set the compiler warning level to 4 (VS 2005 defaults to level 3). By doing this the above code would generate the following warning;
      warning C4706: assignment within conditional expression
      Now you are at least warned that there could be an error in your code, but nevertheless the code is perfectly legal. And if it is not enough to be warned you can of course treat warnings as errors!

      To avoid the C4706 warning when you intend to make your test value the result of an assignment, test to ensure that the assignment is non-zero or not null. For example, the following code will not generate this warning:
      Code:
      if ( ( a = b ) != 0 )
      {
      ...
      }
      In Visual Studio 2005 you set the warning level by doing;
      Project->Properties->Configuration properties->C/C++->General->Warning level.
    Last edited by cilu; February 12th, 2007 at 04:20 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured