Home >Backend Development >C++ >Is `(bool)true` Always Equivalent to `(int)1` in C ?

Is `(bool)true` Always Equivalent to `(int)1` in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 09:49:11946browse

Is `(bool)true` Always Equivalent to `(int)1` in C  ?

Type Casting in C Expressions: (bool)true and (int)1

In C , it is a common practice to use typecasting to convert data from one type to another. This question explores whether we can safely assume the equivalence of (bool)true and (int)1 in C compilers.

The Equivalence

The conversion from bool to int is defined by the C standard in section 4.7 [conv.integral] / 4. It states that if the source type is bool, the value true is converted to one. This means that in the expression (bool)true == (int)1, the bool value will be promoted to an int and will have a value of 1.

Redundant Casting

The casts in the expression (bool)true == (int)1 are technically redundant. The bool value will be automatically promoted to an int by the compiler, and the comparison will work as expected without the explicit casts.

Compiler Compatibility

The equivalence between (bool)true and (int)1 is guaranteed by the C standard. As such, it is a safe assumption to make for any C compiler that adheres to the standard.

Conclusion

In C , we can safely assume (bool)true == (int)1 for all C compilers that follow the C standard. The typecasts are redundant and can be omitted without affecting the result of the comparison.

The above is the detailed content of Is `(bool)true` Always Equivalent to `(int)1` in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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