本文介绍了printf中的前增量和后增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int main()
{
int value = 4321;
int *ptrVal = &value;
printf("%d %d",++value,(*(int*)ptrVal)--);
return 0;
}
上述打印语句中的预增/后增如何工作?
How does pre-increment/post increment works in above print statement ?
为什么回答4321 4321?
And why is answer 4321 4321 ?
推荐答案
您要在两个序列点之间两次修改对象value
:您正在调用未定义的行为.未定义的行为意味着您的程序可以打印4321 4321
,打印42
甚至崩溃.
You are modifying the object value
twice between two sequence points: you are invoking undefined behavior. Undefined behavior means your program can print 4321 4321
, print 42
or even just crash.
您的程序的正确版本为:
A correct version of your program would be:
int value = 4321;
int *ptrVal = &value;
++value;
(*ptrVal)--; // no need to cast to int *
printf("%d %d", value, *ptrVal); // same as printf("%d %d", value, value);
当然,您不需要任何临时指针即可实现这一目标.
Of course you don't need any temporary pointer to achieve this.
这篇关于printf中的前增量和后增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!