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

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

问题描述

我很清楚,修改按值传递的函数参数在 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()函数的作用域内.xdoSomething() 被调用(并且参数被传递)后被定义,并在控制返回后销毁.只要函数调用正在执行(即变量仍在作用域内),参数就与任何其他变量相同,仅由函数调用中提供的参数初始化.

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 内部所做的任何更改该函数不会反射到调用者(实际参数)中,但编译器没有理由抱怨,只要函数内部对 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天全站免登陆