Yashashavi Ym
Yashashavi Ym

Reputation: 19

Uninitialized variable read error

Program to find the sum of digits of a number.

The compiled code gives an error:

runtime failure:variable 'z' is being used without being initialized.

If I initialize 'z' won't it erase the original value of z?

enter code here

#include<iostream>

#include<cmath>
#include<string>
#include<iomanip>
using namespace std;
class sumd
{
int x;
  public:
void getdata()
{
    int z=0;
    cout<<"enter the no";
cin>>x;
z=x;
};
void sumdigit()
{
int z,y,sume,temp;             // this is the line with the error...
for(temp=z;temp>0;temp/=10)
{
    y=temp%10;
sume+=y;
}
cout<<sume;

};
};
  int main()
  {
  sumd s1;
   s1.getdata();
   s1.sumdigit();
   return 0;
      }

Upvotes: 0

Views: 183

Answers (2)

Sylence
Sylence

Reputation: 3083

There is no 'original' value for z at this point. I assume you are thinking that the value of z in the getdata function will be saved? Well it won't. You have to return the value of z from the function and pass it to the sumdigit function

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 373482

I think the problem is that in this method:

void sumdigit()
{
    int z,y,sume,temp;             // this is the line with the error...
    for(temp=z;temp>0;temp/=10)
    {
        y=temp%10;
        sume+=y;
    }
    cout<<sume;
}

You haven't given a value for z or y; they're uninitialized local variables. I think that you probably intended to make z and y data members of the enclosing class. Try moving the definition of those variables outside of this method and see if that fixes things.

Hope this helps!

Upvotes: 4

Related Questions