通过本地修改的值传递的参数会发生什么情况? [英] What happens to a parameter passed by value that is modified locally?

查看:99
本文介绍了通过本地修改的值传递的参数会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很清楚,在C/C ++函数之外,修改按值传递的函数自变量无效,但是编译器允许这样做-但是会发生什么?是该参数的本地副本,并且该函数中的可以修改吗?

I am well aware that modifying a function's argument that is passed by value is ineffective outside of the C/C++ function, but compilers allow it - but what happens? Is a local copy made of the argument and that is modifiable within the function?

#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表示的值保留在什么地方?

Now this always exits without error, but where in the scheme of things (memory space) is the value represented in the function as x kept?

我想(组合的声明和定义)应该开始:

I imagine that should the (combined declaration and definition) begin:

void doSomething( const int x )

任何半个体面的编译器都会打我的手.

I would get my wrists slapped by any half-decent compiler.

推荐答案

对于函数doSomething()x对于该函数而言是本地的.它具有与在函数体开头定义的任何其他变量类似的作用域.

For the function doSomething(), x is local to the function. It has the similar scope of any other variable defined at the beginning of the function body.

一般而言,x仅存在于doSomething()函数的范围内.一旦调用doSomething()(并且传递了参数),并且一旦控件返回,销毁了,便定义了x.只要执行了函数调用(即变量仍在作用域内),参数就与任何其他变量相同,仅由函数调用中提供的参数进行初始化.

In general terms, x exists only in the scope of doSomething() function. x is defined once doSomething() is called (and the argument is passed) and destroyed once the control returns. As long as the function call is being executed (i.e., the variable remains in scope), the parameter(s) are the same as any other variable, only initialized by the arguments supplied in the function call.

引用C11,第§6.2.1章,标识符范围

Quoting C11, chapter §6.2.1, Scopes of identifiers

[...]如果声明符或类型说明符 声明标识符出现在块中或在参数声明列表中 函数定义,标识符具有块作用域,该作用域终止于 关联的块. [...]

[...] 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所做的任何更改都不会 reflect 进入调用者(实际参数),但是只要函数内x上的操作有效,编译器就没有理由抱怨.

As you are already aware, x being the local copy of the actual argument passed to function call, any changes made to x inside the function will not reflect into the caller (actual argument), but there's no reason for the compiler to complain as long as the operation(s) on x inside the function is (are) valid.

这篇关于通过本地修改的值传递的参数会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆