简体   繁体   中英

Why it is assigning a garbage value to variable 'calc'?

This program gives a garbage value to the variable calc .

Can anyone help me? What is the problem here?

Code:

#include <iostream>
using namespace std;

class trial {
public:
    int m1;
    int m2;
    int calc = m1 + m2;
    void setdata(int a1, int a2) {
        m1 = a1;
        m2 = a2;
    }
    void getcalc(){
        cout << "Sum of m1 & m2 is " << calc << endl;
    }
};

int main() {
    trial t1;
    t1.setdata(3, 8);
    t1.getcalc();
    system("pause>0");
    return 0;
}

Output:

Sum of m1 & m2 is -1717986920

The problem is how you defined calc .

When a object trial is initialized, m1+m2 is assigned to calc , but m1 and m2 are not initialized themselves (they contain 'garbage').

When setdata() is called, two user-provided integers are assigned to m1 and m2 , but calc is unchanged, thus the 'garbage' in the output.

You need to update calc by adding calc = m1 + m2; in setdata() .

You are never calculating the sum at first place...

void setdata(int a1, int a2) {
        m1 = a1;
        m2 = a2;
        calc = m1 + m2;
    }

but always initialize the member variables, you are not initializing the m1 and m2, hence garbage values which is assigned by the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM