Determining subroutine argument evaluation order [duplicate]

陌路散爱 提交于 2019-12-20 04:23:56

问题


I am writing a program in C that determines the order in which subroutine arguments are evaluated.

What I have so far is the following:

int i=1;
printf("%d %d %d\n", i++, i++, i);

but I'm not sure If I am on the correct path or would it be easier to write in a different language like Ruby.

How can I write a program in C (or Ruby) that determines the order in which subroutine arguments are evaluated?


回答1:


The order of evaluation of arguments to printf() function is unspecified. So you can't determine portably in which order they are evaluated. If that's what you want to determine then perhaps you'd choose a language where the order of evaluation is well-defined.

Besides, your code has undefined behaviour as you modify i more than once without an intervening sequence point.




回答2:


A way to do this without invoking undefined behavior would be to simply print a message as each argument is evaluated:

#include <stdio.h>

static void foo(int a, int b, int c) {}

static int argument(int n)
{
    printf("Argument %d.\n", n);
    return n;
}

int main(void)
{
    foo(argument(0), argument(1), argument(2));
    return 0;
}

However, that will only show you the order of argument evaluation in one specific execution of the program. The order of argument evaluation is not specified by the C standard and may change for a variety of reasons. For example, if you pass a function simple arguments, the compiler might evaluate them last-to-first so that it can easily put them on the stack in the order required for calling subroutines on that platform. But suppose, with the same compiler version and compilation switches, you pass a function some complex arguments, some of which have common subexpressions. The compiler might decide to evaluate those arguments first, to take advantage of the common subexpressions.

The compiler can even evaluate part of one argument, then part of another, then part of the first, then a third argument, then evaluate an expression preceding the function call (provided sequence point behavior is preserved), then finish the second argument.

The order of argument evaluation is not something you can rely on.



来源:https://stackoverflow.com/questions/13675000/determining-subroutine-argument-evaluation-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!