Home >Backend Development >C++ >Is `true` Always Equivalent to `1` in C Boolean-Integer Conversions?

Is `true` Always Equivalent to `1` in C Boolean-Integer Conversions?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 15:20:10263browse

Is `true` Always Equivalent to `1` in C   Boolean-Integer Conversions?

Boolean-Integer Conversion in C

In the C programming language, it is often necessary to convert between different types of data. One common conversion is between boolean values and integers. The question arises: can we assume that the boolean value true is equivalent to the integer 1 for any C compiler?

The Answer

Yes, it is safe to assume that (bool)true == (int)1 for any C compiler. This is because of the following reasons:

  • Integral Promotion: When a boolean value is converted to an integer, it undergoes a process called integral promotion. This converts the boolean to an int with a value of either 0 (for false) or 1 (for true).
  • Implicit Conversion: Casts are not required for this conversion. The C compiler will automatically perform the implicit conversion based on the context of the expression.

Therefore, the expression true == 1 will evaluate to true, regardless of the C compiler being used. This behavior is specified in the C standard (4.7 [conv.integral]) which states that "If the source type is bool... true is converted to one."

The above is the detailed content of Is `true` Always Equivalent to `1` in C Boolean-Integer Conversions?. 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