C++ Some variables “used uninitialized in this function”. Why?

前端 未结 2 810
滥情空心
滥情空心 2021-01-28 10:06

This is my code:

#include 
using namespace std;

void input_function(int hour, int minutes);
void calcuation(int hour, int minutes, char meri         


        
2条回答
  •  终归单人心
    2021-01-28 10:52

    The error you're getting about uninitialized variables means that the program is trying to use the variables without them being assigned a value. Wikipedia defines them as follows:

    In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.

    To fix these errors you might try to give your variables initial values. The actual number used shouldn't matter unless its to big for the integer.

    Its also very likely that when you fix that, that your program will not do what you expect. That is because currently your functions are accepting parameters, but not actually changing the variables in your int main() function.

    There are a couple of ways to fix this. You could pass by reference:

    void input_function(int& hour, int& minutes)
    {
      //things happen, the & sign before the variables is the important part
    }
    

    Doing this would let the function interact with the variables that you actually want to use, and is probably the best way to tackle this.

    Or if that's confusing might also try declaring them as global variables or making your functions return integer values.

    Best of luck!

提交回复
热议问题