左值和函数结果——依赖?
lvalue and function result -- dependency?
考虑以下片段:
int func(char *ptr);
...
n += func(p + n);
此代码是否会产生未定义的行为,因为函数的参数取决于左值?我假设编译器会计算函数的结果,然后递增 p + n
,或者这可能是特定于编译器的?
在函数调用中函数进入之前有一个序列点。这意味着每个值计算和与参数相关的副作用都在函数调用中进入函数之前完成。
C11-§6.5.2.2/10:
There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call.
所以,如果
n += func(p + n);
p + n
将在函数调用之前计算。
n += func(p + n);
定义明确,因为仅在函数调用完成后才访问 n
进行写入。只有读取n
.
的值才能完成函数调用
考虑以下片段:
int func(char *ptr);
...
n += func(p + n);
此代码是否会产生未定义的行为,因为函数的参数取决于左值?我假设编译器会计算函数的结果,然后递增 p + n
,或者这可能是特定于编译器的?
在函数调用中函数进入之前有一个序列点。这意味着每个值计算和与参数相关的副作用都在函数调用中进入函数之前完成。
C11-§6.5.2.2/10:
There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call.
所以,如果
n += func(p + n);
p + n
将在函数调用之前计算。
n += func(p + n);
定义明确,因为仅在函数调用完成后才访问 n
进行写入。只有读取n
.