Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't the original value getting incremented twice even though I have two increments

I’m new at programming and can someone explain to me how this code work?

#include <iostream>
using namespace std;

int main () {

    int a = 3, b = 4;
    decltype(a) c = a;
    decltype((b)) d = a;
    ++c;
    ++d;


    cout << c << " " << d << endl;
}

I’m quite confused how this code run as they give me a result of 4 4, shouldn’t be like 5 5? Because it was incremented two times by c and d? I’m getting the hang of decltype but this assignment caught me confused how code works again.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

decltype(a) c = a; becomes int c = a; so c is a copy of a with a value of 3.

decltype((b)) d = a; becomes int& d = a; because (expr) in a decltype will deduce a reference to the expression type.

So we have c as a stand alone variable with a value of 3 and d which refers to a which also has a value of 3. when you increment both c and d both of those 3s becomes 4s and that is why you get 4 4 as the output

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading