来自 cppreference:
Between the previous and next sequence point a scalar object must have its stored value modified at most once by the evaluation of an expression, otherwise the behavior is undefined.
代码示例:
int a = store_and_return_value(&a);
对于 C 和 C++。
最佳答案
这是不是 表现出未定义的行为。
C standard 的第 6.5.2.3p10 节状态:
There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function
因此,鉴于您的代码行:
int a = store_and_return_value(&a);
对函数的调用
store_and_return_value
引入一个序列点。假设有一条类似于 *arg = 123;
的行在函数中,这个语句后面还有一个序列点。所以在
store_and_return_value
里面的任何声明取消引用并写入传入的指针的顺序在 a
之后被正式初始化。所以不管store_and_return_value
的 body 是什么包含程序定义良好。
关于c - 在按引用传递时声明变量是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61066606/