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.
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:
*b
(i.e. (*b)++
, *b<=0
, etc.) Something like :int main() {
int b = 2;
while (true) {
slider(&b);
}
}
void slider(int *b) {
// Modify references to b to become *b
}
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
}