Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

c++ - Why am I getting the error "using uninitialized memory 'i'" and "uninitialized local variable 'i' used" when trying to make i = i*i

I am new to C++ and was testing out while loops and the sheer speed of C++ and its toll on my CPU and I got the following errors:

Severity Code Description Project File Line Suppression State Warning C6001 Using uninitialized memory 'i'
Severity Code Description Project File Line Suppression State Error 4700 uninitialized local variable 'i' used

I have no idea how to read an error message and haven't even encountered initializing in C++ yet so I don't have any clue about what to do.

#include <iostream>
using namespace std;
    
int main() {
    long long i = 0;
    while (i < 10000000000000000) {
        long long i = i*i;
        cout << i ;
    }
    cout << i;
    return 0;
}
question from:https://stackoverflow.com/questions/65850709/why-am-i-getting-the-error-using-uninitialized-memory-i-and-uninitialized-l

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the body of the while loop

while (i < 10000000000000000) {
    long long i = i*i;
    cout << i ;
}

you declared the variable i that is not initialized and has an indeterminate value and you are trying to use this indeterminate value to initialize the variable itself.

That is in this declaration

    long long i = i*i;

in the initializer there is used the same declared variable i that hides the declaration of the variable with the same name that appears before the loop

Substitute the declaration for the statement

   i = i*i;

But initially you should set the variable i to some value unequal to 0 for example to 10.

long long i = 10;

Otherwise the result of the expression i * i always will be equal to 0.

Something like

#include <iostream>
using namespace std;

int main() {
    long long i = 10;
    while (i < 10'000'000'000'000'000) {
        i = i*i;
        cout << i ;
    }
    cout << i;
    return 0;
}

Though you should be caution selecting the initial value of the variable i because an overflow can occur in the expression i * i and you can get an infinite loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...