0

So i was not able to get the following code to work. User can pass and store a value to separate function and retrive it later. The function works in 3 ways.

  1. user can reset the value to 0 and return 0
  2. user can set the value to any input and return 0
  3. user can view the stored value by returning the stored value

the code is as follows:

#include <stdio.h>
#include <stdlib.h>
#pragma warning (disable:4996)

int storage(int input, int mode) {

    int value;

    if (mode == 0) { //if mode is zero, storage value is assigned as input
        value = input;
        return 0;
    }
    else { //if mode is non zero, simply return the storage value
        return value;
    }
}

int main(void) {

    int input;

    storage(0, 0); //reset storage value to 0
    printf("out > %d\n", storage(0, 1)); //print storage value, should be 0

    printf("in? > ");
    scanf("%d", &input); //scan input from user
    storage(input, 0); //assign input as new storage value

    printf("out > %d\n", storage(0, 1)); //print new storage value, should be same to input

    return 0;
}

But i keep getting data is uninitialized error:

Severity Code Description Project File Line Suppression State Error C4700 uninitialized local variable 'value' used

I am new to C, so im not exactly sure what to search online and most of the solution arent C, but C# or C++. Any help appreciated.

user438383
  • 5,716
  • 8
  • 28
  • 43
fdhl
  • 1

1 Answers1

0

When you declare int value;, the value is not global. In other words, everytime you call storage, the value variable in the function is a new one, rather than retaining the previous value. Therefore when you return value, you actually returns an uninitialised number.

To solve the error, simply change int value to int value = 0 (give it an initial value), but I hope you could see that this does not make the program behave as expected.

To actually store the value, either declare value globally (move the declaration int value outside of the function), or make it a static variable (static int value).

MMZK1526
  • 654
  • 2
  • 16
  • The part around the initialisation is irrelevant to the actual problem and just drives the reader's attention away from the actual solution – you might consider swapping second and third paragraph (and for currently second/then third indicate explicitly that this is just a side note plus mention that this initialisation is necessary to prevent undefined behaviour if the function is called the very first time in mode 1). – Aconcagua Aug 09 '22 at 13:12