c++ - 腾讯笔试题 printf
迷茫
迷茫 2017-04-17 14:35:40
0
6
583
#include <stdio.h>

int f(int, int, int)
{
    return 0;
}

int main()
{
    return f(printf("a"), printf("b"), printf("c"));


}

这是今天晚上遇到的腾讯在线笔试题目,问题是 “代码结果是什么?”
这道题目结果是 cba 吗?为什么?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(6)
PHPzhong

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. ”

小葫芦

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.

阿神

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.

左手右手慢动作

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.

黄舟

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

洪涛

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template