gpt4 book ai didi

c++ - 函数参数评估顺序

转载 作者:行者123 更新时间:2023-11-30 16:07:42 24 4
gpt4 key购买 nike

在 C 和 C++ 中,函数参数的求值是否有固定的顺序?我的意思是,标准怎么说?是从左到右还是从右到左?我从书中得到了令人困惑的信息。

是否有必要仅使用堆栈来实现函数调用? C 和 C++ 标准对此有何规定?

最佳答案

C 和 C++ 是两种完全不同的语言;不要假设相同的规则总是适用于两者。然而,在参数评估顺序的情况下:

C99:

6.5.2.2 Function calls
...
10 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.

[编辑]C11(草案):

6.5.2.2 Function calls
...
10 There is a sequence point after the evaluations of the function designator and the actualarguments but before the actual call. Every evaluation in the calling function (includingother function calls) that is not otherwise specifically sequenced before or after theexecution of the body of the called function is indeterminately sequenced with respect tothe execution of the called function. 94)
...
94) In other words, function executions do not ‘‘interleave’’ with each other.

C++:

5.2.2 Function call
...
8 The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.

这两个标准都没有强制要求使用硬件堆栈来传递函数参数;这是一个实现细节。 C++ 标准使用术语“展开堆栈”来描述对从 try block 到 throw 表达式 的路径上自动创建的对象调用析构函数,但仅此而已。最流行的架构确实通过硬件堆栈传递参数,但它并不通用。

[编辑]

I am getting confusing information from the books.

这一点也不奇怪,因为 90% 的关于 C 语言的书籍都是垃圾。

虽然语言标准对于学习 C 或 C++ 来说并不是一个很好的资源,但能够方便地解决此类问题还是有好处的。官方™标准文档需要花费大量金钱,但有些草案可以在线免费获得,并且应该足以满足大多数用途。

最新的 C99 草案(自原始发布以来有更新)已发布 here 。最新的预出版 C11 草案(去年已正式批准)已发布 here 。公开可用的 C++ 语言草案 here ,尽管它有明确的免责声明,表明某些信息不完整或不正确。

关于c++ - 函数参数评估顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59557133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com