Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

During code, I've found remarkable problem.

In my code, i just print same object using format string. but result is not same.
By my insight, i thought result is 97 97 97. but outcome is 97 98 99

What happened to them? i can not understand that situation.

Could you explain this?

class A
{
public:
    int a;
    int b;
    int c;
    A(){
        this->a=97;
        this->b=98;
        this->c = 99;
    };
};
int main(int argc, char **argv){
    A a;
    printf("%d %d %d\n", a, a, a);
    return 0;
}
share|improve this question
3  
C#, C++, and C are different languages. For C++, printing a class object with %d is undefined behavior. Vote to close for lack of minimal knowledge of the subject. – Jim Balter 36 mins ago
1  
This poster is clearly a beginner, so instead of closing I suggest rather helping by pointing out the errors & wrongs and what should be done and where to get edifying info ... (PS: it reeks of arrogant elitism to want summary closing) – slashmais 25 mins ago
1  
I think the OP has demonstrated at least minimal knowledge and made an effort to explain both expected and actual results along with a minimal compiling code sample. The only thing wrong with this question was the inappropriate tagging, which has been remedied. – Marcelo Cantos 24 mins ago

2 Answers

a is an object of type A, not an integer, which is what %d requires. This leads to undefined behaviour, which means anything goes. In this case, what appears to be happening is that one of the as after the format string is occupying the same place on the stack that three int parameters would have occupied, and so its data members (a, b and c) are what the three %ds end up using.

To print the value 97 stored in A::a three times, you should do this:

printf("%d %d %d\n", a.a, a.a, a.a);
share|improve this answer

A small rewrite of your code:

class A
{
public:
    int a;
    int b;
    int c;
    A(){
        a = 97;
        b = 98;
        c = 99;
    }
void AFunction(int a, int b, int c){
        this->a = a;
        this->b = b;
        this->c = c;
    }
};
int main(int argc, char **argv){
    A a;
    printf("(Expect: 97 97 97) %d %d %d\n", a.a, a.a, a.a);
    printf("(Expect: 97 98 99) %d %d %d\n", a.a, a.b, a.c);

    a.AFunction(1,2,3);
    printf("(Expect: 1 2 3) %d %d %d\n", a.a, a.b, a.c);

    return 0;
}

Using the this-> syntax in the constructor is not wrong, just unnecessary. In the sample AFunction() it is necessary to use this-> so that the compiler can figure out which a, b or c you are referring to.

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.