c - 在按引用传递时声明变量是未定义的行为吗?

标签 c

来自 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/

相关文章:

c - 定义和声明有什么区别?

c - gdb打印命令的默认格式是什么

c - C语言中的栈,如何实现

c - 文本文件无法在 C 中打开

c - 卡在 do{} while(false) 循环中

c - 多线程同步

c++ - unix 应用程序在发送 SIGINT 时在 fread() 期间挂起

c - 最大子数组的特殊情况

c - 在C中的某个字符之后从字符串中删除文本

c++ - 用 Alpha 保存 OpenGL 输出?