search

Home  >  Q&A  >  body text

Why is it recommended to prioritize constants in "if" statements?

I was looking at some sample C code for a hardware interface I'm using and noticed a number of statements similar to:

if ( NULL == pMsg ) return rv;

I'm sure I've heard people say that putting the constant first is a good idea, but why is that? Is this just so you can quickly see what you're comparing if you have a big statement or is there more to it?

P粉066224086P粉066224086253 days ago491

reply all(2)I'll reply

  • P粉226667290

    P粉2266672902024-03-26 12:47:56

    Prevent you from writing:

    if ( pMsg = NULL ) return rv;

    Hit by mistake. However, a good compiler will warn you about this, so most people won't use the "const-first" way because they find it difficult to read.

    reply
    0
  • P粉180844619

    P粉1808446192024-03-26 09:11:54

    This way there is no confusion between comparison (==) and assignment (=).

    As you know, you cannot assign to a constant. If you try, the compiler will give you an error.

    Basically, this is a defensive programming technique. To protect yourself from yourself.

    reply
    0
  • Cancelreply