Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reasoning behind putting constants in 'if' statements first?

People also ask

What is the point of using declared constants?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value.

What is the advantage of using a named constant?

The name of a named constant is therefore indicative of the value's role. A further advantage of using named constants is that should the given value be modified in the source code, it is sufficient to modify the declaration statement, instead of looking up all the occurrences of the value.

Why do we need if statements in codes?

An if statement lets your program know whether or not it should execute a block of code. Comparison-based branching is a core component of programming. The concept of an if-else or switch block exists in almost every programming language.


So that you don't mix comparison (==) with assignment (=).

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

Basically, it's one of defensive programming techniques. To protect yourself from yourself.


To stop you from writing:

 if ( pMsg = NULL ) return rv;

by mistake. A good compiler will warn you about this however, so most people don't use the "constant first" way, as they find it difficult to read.


It stops the single = assignment bug.

Eg,

if ( NULL = pMsg ) return rv;

won't compile, where as

if ( pMsg =  NULL) return rv;

will compile and give you headaches


To clarify what I wrote in some of the comments, here is a reason not to do this in C++ code.

Someone writes, say, a string class and decides to add a cast operator to const char*:

class BadString
{
public:
   BadString(const char* s) : mStr(s) { }

   operator const char*() const { return mStr.c_str(); }

   bool operator==(const BadString& s) { return mStr == s.mStr; }

   // Other stuff...

private:
   std::string mStr;
};

Now someone blindly applies the constant == variable "defensive" programming pattern:

BadString s("foo");

if ("foo" == s) // Oops.  This compares pointers and is never true.
{
   // ...
}

This is, IMO, a more insidious problem than accidental assignment because you can't tell from the call site that anything is obviously wrong.

Of course, the real lessons are:

  1. Don't write your own string classes.
  2. Avoid implicit cast operators, especially when doing (1).

But sometimes you're dealing with third-party APIs you can't control. For example, the _bstr_t string class common in Windows COM programming suffers from this flaw.


When the constant is first, the compiler will warn you if you accidentally write = rather than == since it's illegal to assign a value to a constant.