c - 是否定义了 _Bool 递增?

标签 c boolean increment undefined-behavior

C 标准将 _Bool 定义为包含 0 或 1 的无符号类型。如果 _Bool 类型的值 1 递增,据我所知,有两个选项:

  • 该值在 1 到 0 之间环绕
  • 该值增加到 2,它是非零值,因此在转换回 _Bool
  • 时变为 1。

    在我的系统上的 GCC 和 Clang 上,行为似乎是后者。这是否由标准明确定义?

    最佳答案

    来自 C 标准(6.3.1.2 boolean 类型)

    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.



    例如 6.5.3.1 前缀自增和自减运算符

    2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1).



    最后 6.5.16.2 复合赋值

    3 A compound assignment of the form E1 op = E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue E1 is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation. If E1 has an atomic type, compound assignment is a read-modify-write operation with memory_order_seq_cst memory order semantics.



    注意(6.3 转换)

    — The rank of _Bool shall be less than the rank of all other standard integer types.



    因此在表达式中使用的类型 _Bool 被转换为具有更高等级的其他类型。

    关于c - 是否定义了 _Bool 递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119285/

    相关文章:

    c - 当进程从另一个进程启动时,为什么 getopt() 得不到第一个参数?

    c - igraph R 和 C,写入和读取带有属性的邻接矩阵

    c# - 无法在 LinQ 查询中将类型 'bool?' 隐式转换为 'bool'?

    c# - 如何在单击按钮时保持 boolean 值的状态?

    c - 究竟如何? : operator work in C?

    c++ - 循环中的前增量和后增量有什么区别(for/while)?

    java - 使用 JNA 从 Java 进行 native C 调用的巨大内存占用

    c - boolean 值的轻量级矩阵

    powershell - 简单的递增/递减计数器

    释放 C ADT 的约定