2017-09-04 43 views
0

如果我初始化这样的变量:为什么常量表达式不给出错误?

static int i = 2 * 2/0; 

然后,编译器给我一个错误。

prog.c: In function 'main': 
prog.c:5:23: warning: division by zero [-Wdiv-by-zero] 
    static int i = 2 * 2/0; 
        ^
prog.c:5:17: error: initializer element is not constant 
    static int i = 2 * 2/0; 

但是,如果我使用||代替*,像这样:

static int i = 2 || 2/0; 

那么它的成功编译。

根据Operator Precedence,优先*高于||。所以,首先2/0操作评估。我对吗?

那么,为什么不static int i = 2 || 2/0;给出错误?

+4

'||'是短路的,所以表达式的第二部分根本不被评估。 – Groo

+3

@格鲁:请在答案部分的答案。 – Bathsheba

+1

更有意思的是询问是否a || 2/0'给出一个错误... –

回答

5

这是由于||强制短路评价和您的表达式作为

static int i = (2 || (2/0)); 

由于2等于2一个表情评估的事实,2/0不评估。

+1

重要的细节是''''等*是保证*是短路。 – hyde

相关问题