函数参数中前增量和后增量的运算顺序?
我有一些 C 代码:
main()
{
int a=1;
void xyz(int,int);
xyz(++a,a++); //which Unary Operator is executed first, ++a or a++?
printf("%d",a);
}
void xyz(int x,int y)
{
printf("\n%d %d",x,y);
}
函数 xyz
有两个传入的参数,++a
和 a++
。有人可以解释操作顺序来解释结果吗?
上面的代码根据使用的编译器打印“3 13”或“2 23”。
I have some C code:
main()
{
int a=1;
void xyz(int,int);
xyz(++a,a++); //which Unary Operator is executed first, ++a or a++?
printf("%d",a);
}
void xyz(int x,int y)
{
printf("\n%d %d",x,y);
}
The function xyz
has two parameters passed in, ++a
and a++
. Can someone explain the sequence of operations to explain the result?
The above code prints "3 13" or "2 23" depending on which compiler is used.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
引用 Kernighan &里奇,第 2.12 章:
Quoting Kernighan & Ritchie, Chapter 2.12:
函数的一元运算符评估序列:
将输出
在我的系统上。这表明首先计算函数的第二个参数。您不应依赖函数参数的求值顺序。它没有定义,所以在不同的系统上它会有所不同。
不过,找到这种行为的好例子还是不错的。
Unary Operator evaluation sequence for a function:
will output
On my system. This indicates that the second parameter of the function is being evaluated first. You should not rely on order of evaluation of function parameters. It is not defined, so it will be different on different systems.
Good job on finding a nifty example of this behavior, though.
对于一元运算符,有前自增(++i)和后自增(i++)。对于预递增,要递增的值将在操作之前添加。例如:
在这种情况下,输出将为 1。在任何其他操作之前,变量“i”会增加值 1,即“cout <<”。 ++我'。
现在,如果我们在同一个函数中进行后置自增:
输出将仅为 0。这是因为增量会在操作之后发生。但既然您想知道如何将它们作为参数传递,那么它就会这样:
当将这些变量作为参数传递时,输出将是:
我希望这有帮助!
For uniary operators, there is the pre-increment (++i) and post-increment (i++). For pre-increment, the value to be incremented will added before an operation. For example:
In this case, the output would be 1. The variable 'i' was incremented by the value of 1 before any other operations i.e. 'cout << ++i'.
Now, if we did the post-increment in the same function:
The output would only be 0. This is because the increment would happen after the operation. But since you want to know about passing them in as parameters, this is how it will go:
When passing in those variables as parameters, the output would be:
I hope this helps!!
好吧,您的示例代码需要考虑两件事:
++a
还是a++
首先求值都是实现 -依赖。a
的值而修改之间没有序列点会导致未定义的行为。因此,您的代码的结果是未定义的。如果我们简化您的代码并删除未指定和未定义的行为,那么我们可以回答以下问题:
Well, there are two things to consider with your example code:
++a
ora++
is evaluated first is implementation-dependent.a
more than once without a sequence point in between the modifications results in undefined behavior. So, the results of your code are undefined.If we simplify your code and remove the unspecified and undefined behavior, then we can answer the question: