Home > Backend Development > C++ > Can `true` and `1` Always Be Considered Equal in C Comparisons Across Different Compilers?

Can `true` and `1` Always Be Considered Equal in C Comparisons Across Different Compilers?

Susan Sarandon
Release: 2024-11-30 01:50:10
Original
164 people have browsed it

Can `true` and `1` Always Be Considered Equal in C   Comparisons Across Different Compilers?

Can Bool and Int Equate in C Across Compilers?

In C , programmers often encounter the need to compare values of different types, such as bool and int. A common question arises: can we safely assume that (bool)true equals (int)1 for any C compiler?

Answer: Yes, but Casts are Redundant

The casts in the expression (bool)true == (int)1 are unnecessary. C automatically promotes the bool value to an int during the comparison. This promotion results in the value 1.

The behavior is defined by the C standard in [conv.integral] / 4:
"If the source type is bool... true is converted to one."

Therefore, the expression true == 1 is equivalent to 1 == 1, which is a true comparison. This behavior is consistent across all C compilers.

The above is the detailed content of Can `true` and `1` Always Be Considered Equal in C Comparisons Across Different Compilers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template