gpt4 book ai didi

c++ - C++ 中的 "sequenced before"和 "Every evaluation in the calling function"

转载 作者:行者123 更新时间:2023-11-28 06:14:42 30 4
gpt4 key购买 nike

调用函数(包括其他函数调用)中的每个评估,如果在被调用函数的主体执行之前或之后没有特别排序,则相对于被调用函数的执行是不确定的排序。

换句话说,函数执行不会相互交错。

“每次评价”是什么意思。

#include <iostream>
using namespace std;
int a = 0;
ing b = 0;
int f(int,int)
{
cout << "call f, ";
cout << "a=" << a << ", ";
cout << "b=" << b << ", ";
return 1;
}

int g()
{
cout << "call g, ";
cout << "a=" << a << ", ";
cout << "b=" << b << ", ";
return 1;
}

int main()
{
f(a++, b++) + g();
return 0;
}
  1. 它意味着函数调用表达式f(a++, b++)的求值,所以a++的求值、b++的求值和f的执行都在g执行之前或之后排序.

    在这种情况下,有两种结果。如果表达式 f(a++, b++) 的求值顺序在 g 执行之前:

    调用 f, a=1, b=1, 调用 g, a=1, b=1,

    如果 g 的执行顺序在表达式 f(a++, b++) 的计算之前:

    调用 g, a=0, b=0, 调用 f, a=1, b=1,

2.表示a++求值,b++求值,f执行。

因此,a++ 的求值可以在 g 执行之前排序,b++ 的求值和 f 的执行可以在 g 执行之后排序。

call g, a=1, b=0, call f, a=1, b=1,
  1. 意思是值(value)计算或副作用。

因此 a++ 的值计算可以在 g 执行之前排序,a++ 的副作用、b++ 的评估和 f 的执行可以在 g 执行之后排序。

call g, a=0, b=0, call f, a=1, b=1,

在这种情况下,

f(a++, b++) + (a = g());
1.value computation of a++
2.execution of g
3.side effect of a++
4.side effect of = (a = 0)
5.evaluation of b++
6.execution of f

call g, a=0, b=0, call f, a=0, b=1,

哪个是对的?还是其他答案?

我不会说英语,也不太擅长英语。

希望你能明白我说的

f(h1(), h2()) + g(h3(), h4())

h1和h2排在f之前,h3和h4排在g之前。

是否可能:

  1. h1

  2. h4

  3. h2

  4. f

  5. h3

  6. g

最佳答案

[expr.post.incr]/1 ... The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. [ Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator. —end note ]...

我的理解是 a++b++ 的副作用必须在 f 的主体执行之前完成,因此在f 一定是a==1b==1。您的示例 #2 和 #3 无法通过一致的实现实现。

g 的调用与对 f 的调用顺序不确定,因此可以观察到增量前或增量后的值。

关于c++ - C++ 中的 "sequenced before"和 "Every evaluation in the calling function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30558980/

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