gpt4 book ai didi

c++ - 通过在本地修改的值传递的参数会发生什么情况?

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:38 24 4
gpt4 key购买 nike

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

引用 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 所做的任何更改该函数不会反射(reflect)到调用者(实际参数)中,但是只要函数内部x上的操作是编译器就没有理由提示(是)有效的。

关于c++ - 通过在本地修改的值传递的参数会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42492905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com