Home > Backend Development > C++ > body text

What is the value of `c` in the following C/C code: `int a = 2; bool b = a; int c = 3 b;`?

Mary-Kate Olsen
Release: 2024-11-19 20:53:02
Original
937 people have browsed it

What is the value of `c` in the following C/C   code: `int a = 2; bool b = a; int c = 3   b;`?

Conversion from bool to int: Guaranteed Values of 0 or 1

A common misconception arises when converting bool values to int. While many compilers appear to store booleans as 0 or 1, the question remains: is this behavior guaranteed?

Question:

Consider the following C code snippet:

int a = 2;
bool b = a;
int c = 3 + b; // 4 or 5?
Copy after login

What will be the value of c: 4 or 5?

Answer:

Yes, c will always be 4 in C and C.

Explanation:

  • C : According to the C standard (§4.5/4), "An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one." Therefore, b is converted to 0.
  • C: In C (§6.3.1.2/1), "When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1." This implies that a is converted to 1 and stored in b.
  • Conversion to int: Converting from _Bool to int is straightforward because int can hold both 0 and 1 (§6.3.1.3). In both cases, the value of b remains unchanged, resulting in c being 3 0 = 4.

The above is the detailed content of What is the value of `c` in the following C/C code: `int a = 2; bool b = a; int c = 3 b;`?. 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