0

If I initialized variable like this:

static int i = 2 * 2 / 0;

Then, compiler give me an error.

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; 

But, If I use || instead of *, like this:

static int i = 2 || 2 / 0; 

then it's successfully compiled.

According to Operator Precedence, Precedence of * higher than ||. So, first 2 / 0 operation evaluated. Am I right?

So, why doesn't static int i = 2 || 2 / 0; give an error?

msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

5

It's due to the mandatory short-circuit evaluation of || and the fact that your expression is evaluated as

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

Because 2 is an expression equal to 2, 2 / 0 is not evaluated.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483