简体   繁体   English

为什么“i”变量在我的程序中没有增加两次?

[英]Why is “i” variable not getting incremented twice in my program?

Why is "i" variable getting incremented twice in my program? 为什么“i”变量在我的程序中增加两倍?

I modified the question but why is the output different. 我修改了问题,但为什么输出不同。 shouldn't it be same?.? 不应该一样吗?

Code :- 代码: -

#include<stdio.h>
#define MAX(x,y) (x)>(y)?(x):(y)
void main(void)
{
    int i = 10;
    int j = 5;
    int k = 0;
    k == MAX(i++, ++j);
    printf("%d %d %d",i,j,k);
}

Output :- 11 7 0 输出: - 11 7 0

Shouldnt the output be 12 6 0 输出不应该是12 6 0

Use braces around your macro definitions: 在宏定义周围使用大括号:

#define MAX(x,y) ( (x)>(y)?(x):(y) )

The expanded expression (with the original macro definition) 扩展表达式(使用原始宏定义)

k == (i++)>(++j)?(i++):(++j);

groups as 团体为

(k == i++ > ++j) ? i++ : ++j;

i++ > ++j evaluates to 1 , which is unequal to k ( k is 0), so the third operand of ?: ( ++j ) is evaluated. i++ > ++j计算结果为1 ,它不等于kk为0),因此计算了?: ++j )的第三个操作数。 So, i is incremented once, j twice, and k wasn't changed since its initialization, hence your output. 因此, i增加一次, j两次,并且k自初始化后没有改变,因此输出。

The problem is that the macro expands into this: 问题是宏扩展到这个:

k == i++ > ++j ? i++ : ++j;

Operator precedence dictates that > has higher prio than == which has higher prio than ?: So the above is equivalent to this: 运算符优先级指示>具有比==更高的prio,其prio高于?:所以上面的等价于:

(k == (i++ > ++j)) ? i++ : ++j;

i++ and ++j are executed first. 首先执行i++++j Since i++ > j++ gets evaluated to true (1), we get this: 由于i++ > j++被评估为true(1),我们得到:

(k == 1) ? i++ : ++j;

Then since k is 0, k == 1 is evaluated to false (0). 然后,因为k是0,所以k == 1被评估为假(0)。 We get: 我们得到:

0 ? i++ : ++j;

And therefore ++j is executed once more. 因此++ j再次执行。


(As a side note, this expression is well-defined, because the conditional operator has a sequence point between the condition and the evauluation of the 2nd or 3rd operand.) (作为旁注,这个表达式是明确定义的,因为条件运算符在条件和第二或第三个操作数的evauluation之间有一个序列点。)

k == MAX(i++, ++j);

is replaced as 被替换为

k == (i++)>(++j)?(i++):(++j);

Here i=10 , j=5 . 这里i=10j=5 so 所以

k == (10++)>(6)?(11++):(++6); 

so it that expression while checking condition i is incremented once after checking the condition due to post increment and j also incremented once. 因此,检查条件i表达式在检查由于后期增量引起的条件后增加一次,并且j也增加一次。 But 10 > 6 condition is true. 10 > 6条件是正确的。

(k == 1 )?(i++):(++j); // here i=11 and j=6

(k == 1 )? (11++):(++6);

so here k==1 condition fails. 所以这里k==1条件失败。 it will not evaluate i++ in that expression, it will evaluate ++j and return it. 它不会在该表达式中评估i++ ,它会评估++j并返回它。 here i is remains 11 and j become 7. 在这里, i是11岁, j变为7岁。

So you will get 11 7 0 as output. 所以你将得到11 7 0作为输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM