gpt4 book ai didi

在不丢失函数之前拥有的数据的情况下调用函数?

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:03 25 4
gpt4 key购买 nike

我很早就养成了使用全局变量的坏习惯,所以我一直在尝试通过使用局部变量和学习按引用/值调用来拉开距离,这并不是很糟糕,直到我遇到这样的问题,说我有一个函数 Menu() ,它包含一个主菜单和一个数组,然后从菜单中我会转到一个函数并对数组做一些事情,现在我通常会卡在这里我的函数通常是 void 类型的,但通常对于我的程序,我使用 if 选择返回菜单,例如 If(userinput ==2){Menu();} 通常这会导致两个问题 1. 当我进入菜单时,它会重置所有变量值2.如果我在多个地方都有这个函数,它会开始给我参数错误。

这些问题让我很沮丧,让我倾向于全局变量。

Example:

menu(){
int array[100];
functionadd(array);
}

functionadd(array[])
{
int userinput;
do{
//lets the just say here the program does things to my array.
// usually when I want to go back to the menu I'd do something like this
printf("Again or back to menu?1(Again) or 2(Menu)")
scanf_s("%d%[^\n]", &userinput); '\n'==getchar();
} while(userinput == 1)
if(userinput != 2){Menu();} /*this would bring me back to
the menu but my array would be back to as its original state
when it was called in Menu I understand why this happens I
just need to learn how to counter act it*/
}

最佳答案

一些伪代码没有变量被静态关键字“重置”:

int Menu(){
static int remember = 0;
remember++;
return remember;
}

int main(){
printf("remember = %d\n", Menu());
printf("remember = %d\n", Menu());
printf("remember = %d", Menu());
}

输出:

记住 = 1

记住 = 2

记住 = 3

注意,正如 Ron 所说,全局变量是程序生命周期内的变量。静态变量也是如此,但在这种情况下,它不能在另一个函数中访问。此外,静态变量并不是真正的线程安全

"All non-local state must be accessed through atomic operations and the data-structures must also be reentrant."

关于在不丢失函数之前拥有的数据的情况下调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29162438/

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