从函数内部修改参数指向的对象是否符合标准?
Is modifying an object pointed to by a parameter from inside of a function standard-compliant?
如果一个函数修改了它接收到的指向的对象,那么在函数调用之后,调用方是否可以看到该更改?
单位一:
void foo(int *bar) { *bar = 42; }
单位b:
extern void foo(int *bar);
void baz(void) {
int qux = 0;
foo(&qux);
// Is qux guaranteed to be 42 now?
}
我很确定是的,但我想根据 C 标准对其进行备份。
"I'm quite sure it is but I would like to have it backed up based on the C standard."
虽然这是一个非常基本的问题(您可能已经知道),但这里是提供您想要的完整标准合规性的引述:
ISO/IEC 9899:2018 (C18),“函数调用”6.5.2.2/4(强调我的):
"An argument may be an expression of any complete object type. In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument.97)
97) A function can change the values of its parameters, but these changes cannot affect the values of the arguments. On the other hand, it is possible to pass a pointer to an object, and the function can then change the value of the object pointed to. A parameter declared to have array or function type is adjusted to have a pointer type as described in 6.9.1."
如果一个函数修改了它接收到的指向的对象,那么在函数调用之后,调用方是否可以看到该更改?
单位一:
void foo(int *bar) { *bar = 42; }
单位b:
extern void foo(int *bar);
void baz(void) {
int qux = 0;
foo(&qux);
// Is qux guaranteed to be 42 now?
}
我很确定是的,但我想根据 C 标准对其进行备份。
"I'm quite sure it is but I would like to have it backed up based on the C standard."
虽然这是一个非常基本的问题(您可能已经知道),但这里是提供您想要的完整标准合规性的引述:
ISO/IEC 9899:2018 (C18),“函数调用”6.5.2.2/4(强调我的):
"An argument may be an expression of any complete object type. In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument.97)
97) A function can change the values of its parameters, but these changes cannot affect the values of the arguments. On the other hand, it is possible to pass a pointer to an object, and the function can then change the value of the object pointed to. A parameter declared to have array or function type is adjusted to have a pointer type as described in 6.9.1."