Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Why do I need to initialize an int variable to 0?

I just made this program which asks to enter number between 5 and 10 and then it counts the sum of the numbers which are entered here is the code

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int a,i,c;
    cout << "Enter the number between 5 and 10" << endl;
    cin >> a;
    if (a < 5 || a > 10)
    {
        cout << "Wrong number" << endl;
        system("PAUSE");
        return 0;
    }
    for(i=1; i<=a; i++)
    {
        c=c+i;
    }
    cout << "The sum of the first " << a << " numbers are " << c << endl;
    system("PAUSE");
    return 0;
}

if i enter number 5 it should display

The sum of the first 5 numbers are 15

but it displays

The sum of the first 5 numbers are 2293687

but when i set c to 0

it works corectly

So what is the difference ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Because C++ doesn't automatically set it zero for you. So, you should initialize it yourself:

int c = 0;

An uninitialized variable has a random number such as 2293687, -21, 99999, ... (If it doesn't invoke undefined behavior when reading it)

Also, static variables will be set to their default value. In this case 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...