#include <stdio.h>
int f(int, int, int)
{
return 0;
}
int main()
{
return f(printf("a"), printf("b"), printf("c"));
}
这是今天晚上遇到的腾讯在线笔试题目,问题是 “代码结果是什么?”
这道题目结果是 cba 吗?为什么?
PHPz2017-04-17 14:37:40
It’s enough for Tencent to raise issues with this kind of undefined behavior. It is recommended to answer "It doesn't matter whether the result is cba or not. The important thing is not to write such code in daily work - try not to write too many function calls in one line of code, unless it is a chain call; for function calls with side effects, It must be written in multiple lines. ”
高洛峰2017-04-17 14:37:40
Most calling conventions push the stack from right to left, that is, the rightmost parameter is pushed onto the stack first, such as f(a, b, c), then c is pushed onto the stack first, followed by b, and finally a. . Specifically for you, the first thing that is pushed onto the stack is the return value of printf("c"), so a call to printf("c") will be made here. Therefore, the function calling sequence of this code is ultimately printf("c"), printf("b"), printf("a"), f(1,1,1). So the code result is cba.
阿神2017-04-17 14:37:40
The default Calling Convention in C language is cdecl, which means pushing the stack from right to left. However, the order of parameter list evaluation is undefined behavior, and commas in function parameter lists are not sequence points. The debug version of msvc and x86 gcc seem to evaluate from right to left, but as far as I know, Sparc seems to be the other way around. As for the optimized release version, it is even less certain.
ringa_lee2017-04-17 14:37:40
The test is about the direction of pushing parameters onto the stack, and the answer is cba, which is explained very well above.
What I want to say is that I remember that there is a confidentiality agreement for the test questions in front of the Tencent written test questions. There is nothing wrong with pursuing answers to technical questions, but the question owner must also follow the agreement you have agreed to.
黄舟2017-04-17 14:37:40
The order of parameter passing is not equal to the order of evaluation, which means that this question should be wrong, but if you choose, it is recommended to choose cba, because the calling convention is mostly to pass parameters from right to left, and the questioner may misunderstand it. The same is true for the evaluation order
PHP中文网2017-04-17 14:37:40
But the main function returns the f function, and the return value of the f function is 0, so why is the return value of the main function not 0?