Operator precedence in C for the statement z=++x||++y&&++z

后端 未结 4 1570
感情败类
感情败类 2021-01-16 09:48

I was studying operator precedence and I am not able to understand how the value of x became 2 and that of y and z is

4条回答
  •  既然无缘
    2021-01-16 10:39

    The and && and the or || operation is executed from left to right and moreover, in C 0 means false and any non-zero value means true. You write

    x=y=z=1;
    z= ++x || ++y && ++z;
    

    As, x = 1, so the statement ++x is true. Hence the further condition ++y && ++z not executed.

    So the output became:

    x=2 // x incremented by 1
    y=1 // as it is
    z=1 // assigned to true (default true = 1)
    

    Now try this,

    z= ++y && ++z || ++x ;
    

    You will get

    x=1 // as it is because ++y && ++z are both true 
    y=2 // y incremented by 1
    z=1 // although z incremented by 1 but assigned to true (default true = 1)
    

    And finally try this:

    int x = 1;
    int y = 0;
    int z = 1;
    
    z= y && ++z || ++x;
    

    The output will be:

    So the output became:

    x=2 
    y=0 
    z=0 
    

    Because, now the statement for z is look like this:

    z = false (as y =0) && not executed || true
    z = false || true
    z = true
    

    So, y remains same, x incremented and became 2 and finally z assigned to true.

提交回复
热议问题