After changing the value of a variable, how to keep it from changing back when repeated in a loop (inside a function) in C

huangapple go评论64阅读模式
英文:

After changing the value of a variable, how to keep it from changing back when repeated in a loop (inside a function) in C

问题

我是一名学生,正如你所看到的,我目前正在学习C语言。我写了一个代码,它的作用是打印一个可以通过按下a和d键来控制的滑块。变量b是我用来移动滑块的

问题在于,当我在while循环中使用这段代码时,如果没有全局变量或者在函数内部使用它,我无法让它正常工作,因为在每次重复后b的值会返回到2

我确切需要的是让它像当前代码的形式一样工作,但不使用全局变量,并将代码保留在一个单独的函数内部。在这个项目中禁止使用全局变量(所以请告诉我除了int b=2;之外的代码中是否有其他东西被视为全局变量),而滑块是一个更大项目的一部分,所以它将在一个函数内被调用。
英文:

I'm a student and, as you can see, I'm currently studying C. I've written a code that is meant to print a slider that can be controlled by a and d. b is the variable I use to move the slider.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int b = 2;
void slider();

int main() {
    //int Ar[5] = {};


    while (true) {
        
        slider();

    }

}


void slider() { 
    int Ar[5] = {};
    
    switch (_getch()) {
    case'a':
        Ar[b] = 0;
        b--;
        if (b <= 0)
            b = 0;
        Ar[b] = 1;
        break;
    case'd':
        Ar[b] = 0;
        b++;
        if (b >= 4)
            b = 4;
        Ar[b] = 1;
        break;
    }
    for (int i = 0; i < 5; i++) {
        if (Ar[i] == 1)
            printf("|");
        else
            printf("-");
    }
    printf("\n");
    
}

The problem is that when I use this code without a global variable or inside a function and use that inside the while loop, I cannot get it to work as b will return to the value of 2 after each repetition.

What I exactly need is for it to work just like it does in the current form of the code but without using a global variable and keeping the code inside a separate function. Global variables are banned in this project (so please tell me if anything else in that code except int b=2; counts as a global variable), and the slider is part of a bigger project, so it will be called inside a function.

答案1

得分: 0

问题出在变量的作用域。在函数中声明并初始化的变量在每次调用函数时都会被重新初始化为相同的值。在函数返回后,这些变量将不再有效,函数调用之间也无法跟踪它们。

根据您所允许使用的内容,有一些不同的选择:

  1. 使用静态函数变量。在函数中,将b声明为静态变量,这将使变量的值在函数调用之间保持在作用域内。这从技术上来说不是全局变量,所以根据您所述的标准,这可能是被允许的。静态变量不会像其他函数变量一样位于堆栈上,而是位于与其他全局变量相同的内存位置中,但只有声明它的函数才能访问它。

  2. 不确定您是否已经了解指针,但另一种选择是在主函数中跟踪该值,并将该值作为指向修改它的函数的指针传递。这将允许在函数调用之外跟踪该值,并在函数中进行修改。如果采用这种方式,滑块函数在检查或修改b的值的任何地方都必须进行修改以使用*b(例如 (*b)++*b<=0 等)。类似于:

int main() {
    int b = 2;
    while (true) {
        slider(&b);
    }
}

void slider(int *b) {
    // 修改对b的引用以变为*b
}
  1. 另一种不使用静态或指针的选择是由主函数声明和跟踪b,但不是传递指针,而是返回b的新值,以便主函数可以更新它。类似于:
int main() {
    int b = 2;
    while (true) {
        b = slider(b);
    }
}

int slider(int b) {
    // 函数不变
    // ...
    return b; // 在最后一行返回,以便主函数可以跟踪当前值
}

希望这些解释对您有所帮助。

英文:

The problem is scope of the variable. Variables declared and initialized in the function will be re-initialized with the same value every time the function is called. The variables will no longer be valid after the function returns and nothing is tracked across function calls.

There are a few options depending on what you are allowed to use:

  1. Use a static function variable. In the function, declare b as static and this will keep the variables value in scope across function calls. This is technically not a global variable so it might be allowed based on your stated criteria. Static variables will not be on the stack like other function variables, but will be in the same memory location as other global variables are created in the actual application, but only the function that declares it will have access to it.
  2. Not sure if you have done pointers yet, but another option is to track the value in main and pass the value in as a pointer to the function that modifies it. This would allow for the value to be tracked externally from the function call and be modified in the function. If doing this way the slider function would have to be modified every where the value of b is checked or modified to use *b (i.e. (*b)++, *b&lt;=0, etc.) Something like :
int main() {
    int b = 2;
    while (true) {
        slider(&amp;b);
    }
}


void slider(int *b) {
// Modify references to b to become *b
} 
  1. Another option that doesn't use static or pointers is to have main declare and track b, but rather than passing in a pointer return the new value of b so that main can update it. Something like:
int main() {
    int b = 2;
    while (true) {
        b = slider(b);
    }
}


int slider(int b) {
// Function unchanged
...
    return b; //return at end of last line so that main can track current value
}

huangapple
  • 本文由 发表于 2023年6月4日 23:33:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定