如何在参数函数调用进行评估? [英] How are arguments evaluated in a function call?

查看:122
本文介绍了如何在参数函数调用进行评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个code:

void res(int a,int n)
{
    printf("%d %d, ",a,n); 
}

void main(void) 
{
    int i; 
    for(i=0;i<5;i++)
        res(i++,i);
    //prints 0 1, 2 3, 4 5

    for(i=0;i<5;i++)
        res(i,i++);
    //prints 1 0, 3 2, 5 4
}

综观输出,似乎参数不从右到左每一次评估。究竟发生在这里?

Looking at the output, it seems that the arguments are not evaluated from right to left every time. What exactly is happening here?

推荐答案

的参数评价的函数调用的顺序是不确定的。编译器可以评估他们在任何顺序可能决定。

The order of evaluation of arguments in a function call is unspecified. The compiler can evaluate them in whichever order it might decide on.

从C99标准6.5.2.2/10函数调用/语义

From the C99 standard 6.5.2.2/10 "Function calls/semantics":

功能指示符,实际的论点评估的秩序,
  实际的参数内SUBEX pressions是不确定的,但有一个序列点
  前实际调用。

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

如果您需要确保一个特定的顺序,使用临时是通常的解决方法:

If you need to ensure a particular ordering, using temporaries is the usual workaround:

int i; 
for(i=0;i<5;i++) {
    int tmp = i;
    int tmp2 = i++;

    res(tmp2,tmp);
}

更重要的是(因为它导致不确定的行为,不只是不确定的行为)是,你一般不能用一个操作数的递增/递减运算符不止一次在离pression。这是因为:

Even more important (since it results in undefined behavior, not just unspecified behavior) is that you generally can't use an operand to the increment/decrement operators more than once in an expression. That's because:

在previous和下一个序列点之间的对象应具有其存储的值由前pression评价修改最多一次。此外,前一个值是只读,以确定要被存储的值。 (6.5 / 2防爆pressions)

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored. (6.5/2 "Expressions")

这篇关于如何在参数函数调用进行评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆