c-通过本地修改的值传递的参数会发生什么情况?
作者:互联网
我很清楚,修改通过值传递的函数参数在C/C++函数之外无效,但是编译器允许这样做-但是会发生什么?是否由参数构成本地副本,并且可以在函数中进行修改?
#include <stdio.h>
void doSomething( int x )
{
x = 42;
printf( "The answer to Life, the Universe and Everything is (always): %i!\n", x );
}
int main( int argc, char **argv )
{
int a = 0;
doSomething( a );
return -a;
}
现在,这总是无错误地退出,但是在事物方案(内存空间)中函数中以x表示的值保留在哪里?
我想(合并的声明和定义)应该开始:
void doSomething(const int x)
我会被任何不正派的编译器打败.
解决方法:
对于函数doSomething(),x在函数本地.它具有与在函数体开头定义的任何其他变量类似的作用域.
一般而言,x仅存在于doSomething()函数的范围内.一旦doSomething()被调用(并且传递了参数)就定义了x,并在控件返回后销毁了x.只要执行了函数调用(即变量仍在作用域内),参数就与任何其他变量相同,仅由函数调用中提供的参数进行初始化.
引用C11,第§6.2.1章,标识符范围
[…] If the declarator or type specifier that
declares the identifier appears inside a block or within the list of parameter declarations in
a function definition, the identifier has block scope, which terminates at the end of the
associated block. […]
如您所知,x是传递给函数调用的实际参数的本地副本,对函数内部对x所做的任何更改都不会反映到调用方(实际参数)中,但是编译器没有理由抱怨因为该函数内部x上的操作有效.
标签:c-3,c,arguments,parameter-passing,parameters 来源: https://codeday.me/bug/20191013/1904620.html