Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mozilla C/C++ coding style

Today I was going through the "Mozilla Coding Style Guideline" and I found a point I am not sure about.

What do they mean with the following statement?

Do not compare x == true or x == false. Use (x) or (!x) instead. x == true, in fact, is different from if (x)!

I am not sure how these two methods are different. Please clarify.

like image 478
RaverTiny Avatar asked Jul 11 '26 17:07

RaverTiny


1 Answers

Evaluation of x == true and/or x == false depends on the definitions of true and false, which may not be universally the same.

(x) and (!x) are evaluated based on the value of x only and does not depend on any platform / implementation / standard specific definitions. For example, (x) will be evaluated to produce a TRUE result in case of x having a non-zero value.

In C, as per C11 standard, stdbool.h header, chapter 7.18 the definition of true and false are

true

which expands to the integer constant 1,

false

which expands to the integer constant 0

so, in case of x having a value 2

  • x == true will be evaluated to produce FALSE.
  • (x) will produce TRUE.

So, to produce a robust code and maintain portability, it's better to use the later approach.

like image 50
Sourav Ghosh Avatar answered Jul 14 '26 12:07

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!