简体   繁体   English

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

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

One of my friend showed me this program and asked me why is i variable getting incremented twice. 我的一个朋友给我看了这个节目,问我为什么i的变量越来越递增两次。

According to my understanding MAX(i++, ++j); 根据我的理解MAX(i++, ++j); in this line i is first send as a parameter and then incremented, so if the initial value of i is 10 then the incremented value should be 11 , but it shows the incremented value of i as 12 . 在这一行中, i首先作为参数发送然后递增,所以如果i的初始值是10则递增的值应该是11 ,但是它将i的递增值显示为12

Program : 计划:

#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 : 输出:

12 6 11 12 6 11

Can someone please explain me how is the value incremented to 12 ? 有人可以解释一下我的价值如何增加到12?

Thanks. 谢谢。

MAX is a macro, not a function. MAX是宏,不是函数。 In your use case, it expands to: 在您的用例中,它扩展为:

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

你的宏替换意味着你写(i++)>(++j)?(i++):(++j)

Your macro definition contains the arguments twice 您的宏定义包含两次参数

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

Which makes 这使得

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

expand to 扩展到

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

And thus, increments twice. 因此,增加两倍。

MAX is not a function. MAX不是一个功能。 i is not send as a parameter. i不是作为参数发送的。

MAX is a macro. MAX是一个宏。 It is text-replaced where it's used: 它在使用时被文本替换:

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

Now you know why it is incremented twice. 现在你知道为什么它会增加两倍。

Macro do simple text substitution, so after macro expansion, the k = MAX(i++, ++j); 宏做简单的文本替换,所以宏扩展后, k = MAX(i++, ++j); line is seen by the compiler as : 编译器将该行视为:

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

Your MAX macro expands to 你的MAX宏扩展为

(i++)>(++j)?(i++):(++j)

showing why you get a double increment. 显示为什么你得到双增量。

The macro will be expanded to something like in pseudo-C code : 宏将扩展为伪C代码:

if( i++ > j++)  // i is incremented the first time,  j is incremented once
   return i++;  // i is incremented the second time
else
   return j++;  // we never go there, so j is not incremented twice

When using MAX(i++, ++j) , the generated code will be : 使用MAX(i++, ++j) ,生成的代码将是:

(i++) > (++j) ? (i++) : (++j)

Using preprocessor macro just expand the code and copy/paste the arguments in place. 使用预处理器宏只需展开代码并复制/粘贴参数。 You might want to use a function for this case. 您可能希望在这种情况下使用函数。

int max(int x, int y)
{
  return (x > y ? x : y);
}

Modern compiler will inline it while respecting the original behavior of the function call. 现代编译器将在尊重函数调用的原始行为的同时对其进行内联。

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

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