什么是C中的&&&操作

man*_*m-n 195 c c++ operators gcc-warning compiler-optimization

#include <stdio.h>

volatile int i;

int main()
{
    int c;

    for (i = 0; i < 3; i++) 
    {
         c = i &&& i;
         printf("%d\n", c);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面编译的程序的输出gcc

0
1
1
Run Code Online (Sandbox Code Playgroud)

使用-Wall-Waddress选项,gcc发出警告:

warning: the address of ‘i’ will always evaluate as ‘true’ [-Waddress]
Run Code Online (Sandbox Code Playgroud)

如何c在上述计划中进行评估?

Luc*_*ore 272

它是c = i && (&i);,第二部分是多余的,因为&i永远不会评估false.

对于用户定义的类型,你可以实际上重载一元operator &,它可能是不同的,但它仍然是一个非常糟糕的主意.

如果你打开警告,你会得到类似的东西:

警告:'i'的地址将始终评估为'true'

  • @anishsane:无论如何,取一个标签地址的`&&'运算符是非标准的gcc扩展名.但即使它是标准的,最大的munch规则也会阻止它被解析(除非你插入一个空格). (5认同)
  • @anishsane`i`定义为`int`,问题中没有标签.还有,最大的蒙克...... (4认同)
  • @Adrian不,您的代码只显示未定义的行为. (2认同)

Kei*_*son 118

&&&C中没有运算符或令牌.但是&&(逻辑"和")和&(一元地址或按位"和")运算符确实存在.

通过最大的蒙克规则,这个:

c = i &&& i;
Run Code Online (Sandbox Code Playgroud)

相当于:

c = i && & i;
Run Code Online (Sandbox Code Playgroud)

它设置c为1,如果这两个i&i是真实的,为0;如果其中一方是假的.

对于int,任何非零值都为true.对于指针,任何非null值都为true(并且对象的地址始终为非null).所以:

c如果i非零,则设置为1 ,或者0如果等于零,则设置为1 i.

这意味着&&&这里使用的只是故意混淆.作业也可以是以下任何一种:

c = i && 1;
c = !!i;
c = (bool)i;          // C++ or C with <stdbool.h>
c = i ? 1 : 0;        /* C */
c = i ? true : false; // C++
Run Code Online (Sandbox Code Playgroud)