(布尔)可靠地转换为0或1吗? [英] Is (bool) cast reliably 0 or 1?

查看:122
本文介绍了(布尔)可靠地转换为0或1吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自某些上阅读

From some reading on Stack Overflow, I gather that bool, as defined in stdbool.h, is a macro that expands to the built-in type _Bool, and that true is defined as 1 and false is defined as 0.

是否强制转换为bool返回值01?可能_Bool变量(包括强制转换值)是否达到0或1以外的值?

Is casting to bool guaranteed to return a value of 0 or 1? Might a _Bool variable, including cast rvalues, ever attain a value other than 0 or 1?

以下代码暗示_Bool变量(包括强制转换值)将仅具有01值,但是我想确认这一点是可以保证的,并且我没有观察到目标-或特定于编译器版本的行为.

The following code implies that _Bool variables, including cast rvalues, will only have values of 0 or 1, but I'd like to confirm that this is guaranteed, and that I'm not observing target- or compiler version-specific behavior.

(FWIW,我最特别感兴趣的是确认仅强制转换为_BoolNULL0,并且强制转换为_Bool的所有其他可能的指针值将是)

(FWIW, I'm most specifically interested in confirming that only NULL, cast to _Bool, will be 0, and that all other possible pointer values, cast to _Bool, will be 1)

$ cat ./main.c
#include <stdio.h>
#include <stdbool.h>

int main( int argc, char* argv )
{
  int   i;
  int*  p = &i;
  int*  n = NULL;

  printf( "%zu\n", sizeof( (bool)p ) );
  printf( "%p - %d\n", p, (bool)p );
  printf( "%p - %d\n", n, (bool)n );
  printf( "%d\n", (bool)3 );

  return 0;
}

$ gcc --version
gcc (GCC) 8.2.1 20181215 (Red Hat 8.2.1-6)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ gcc -g ./main.c && ./a.out    
1
0x7ffdac3290bc - 1
(nil) - 0
1

推荐答案

C 2018 6.3.1.2 1说:

C 2018 6.3.1.2 1 says:

将任何标量值转换为_Bool时,如果值比较等于0,则结果为0;否则,结果为0.否则,结果为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.

这篇关于(布尔)可靠地转换为0或1吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆