Why is it recommended to prioritize constants in "if" statements?
P粉066224086
P粉066224086 2024-03-25 18:17:36
0
2
443

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粉066224086
P粉066224086

reply all(2)
P粉226667290

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.

P粉180844619

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!