This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Avoid An Equals Typo
  Submitted by



(This is) a tip a friend of mine told me recently and since then I've been using it frequently as it avoids possible bugs. It's about the '=' vs '==' test operator in expressions. C and C++ use '==' for that. However sometimes you make a typo, and type just '=' instead of '=='. Because the single '=' can still make the expression a legal expression, the compiler won't fail in most cases, but you want it to fail. How can you make the compiler to report an error on the spot of the typo?

Consider the following C/C++ code. It contains a typo, but it will compile and run. Because it compiles and runs, you won't see the error you've made. The code is of course just for explanation purposes ;)

// in one of your .h files
#define    FOOSOMEVALUE    100

int iFoo;

// some code which sets iFoo to a certain value // now we have to test if iFoo is equal to FOOSOMEVALUE // and do something if it is. if(iFoo=FOOSOMEVALUE) { // do something }



Now, you can also write the if-statement as:

if(FOOSOMEVALUE==iFoo) 





If you now make the same typo, the compiler will report an error: you can't assign a value to a constant. You have now succesfully avoided the bug, by simply switching the two operands of the expression. :) It seems unnatural at first, but helps to avoid bugs.

FB


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.