0

Having issues with my code... the program compiles, but then it gives the following statement "Run-Time Check Failure #3 - The variable 'result' is being used without being initialized." It then ends the program at that point. Everything I have after trying to run the function is ignored. What should I do?

double result;
    for (int i=0; i<nRows; i++)
    {
        absum.push_back(vector<double>());
        for (int j=0; j<nColumns; j++)
        {
            double temp;
            temp = matrixa[i][j]+matrixb[i][j];
            absum[i].push_back(temp);

            cout << temp << '\t';
        }
        cout << endl;
    }
return result;
d-money
  • 21
  • 1
  • 2
  • 7
  • 1
    Initialize the variable? – Emil Laine Mar 10 '15 at 20:02
  • 3
    You are not initializing or assigning to `result` at all and if you [use the variable then you are invoking undefined behavior](http://stackoverflow.com/q/23415661/1708801) so anything can happen including halting your program. What do you expect the result to be? – Shafik Yaghmour Mar 10 '15 at 20:04
  • Either initialize `result` to some value or don't use its value. What's the mystery here exactly? – David Schwartz Mar 10 '15 at 20:05
  • Does the function *need* to return a value? If so, what is the value? – Thomas Matthews Mar 10 '15 at 20:12
  • It looks like you forgot to enable a good set of warnings (or ignored the warnings produced). For GCC, I recommend `-Wall -Wextra -Wwrite-strings` as a minimum; consider also `-Wpedantic -Warray-bounds` for identifying some other common mistakes. Add `-Werror` if the problem is you failing to heed the warnings! – Toby Speight Apr 11 '18 at 08:46

2 Answers2

4

At the top of your code you have:

double result;

At the moment it's not initialised to anything at all, so the compiler won't use it. So you need to need to initialise it thus:

double result = 0;

It's also generally good practice to initialise every variable you use in C++, that way you don't get nasty compiler messages, and don't run the risk of returning some random chunk of memory. You always want to start your program from a known state, so if you know that result is 0, then all is good.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
2

C++ is picky about this sometimes, have you tried double result = 0?

Jed Estep
  • 585
  • 1
  • 4
  • 15
  • This is neither C++ getting picky, nor C++ at all. It's Microsoft's compiler that can be [configured](https://learn.microsoft.com/en-us/cpp/build/reference/rtc-run-time-error-checks) to emit run-time checks that would otherwise go unnoticed. In terms of C++ the code in question exhibits Undefined Behavior, and it appears the OP ignored their compiler's warnings. It's a good thing someone configured their compiler for them so that they cannot ignore their bug. Of course, someone could have configured their compiler to raise all warnings and treat warnings as errors. – IInspectable Feb 12 '21 at 09:26