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

2

8

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.

Ellieellinger answered 23/8, 2022 at 13:4 Comment(7)
decltype gives you the type of a variable so decltype(a) = int . So it's the same as int c = a; I think you can take it from there.Gunpoint
@AdrianMole d is a reference as decltype(paren-expr) deduces to a reference type.Reply
@Reply Ooh - missed that bit.Contracted
If you're new to C++, then don't mess about with decltype corner cases. This is a highly technical question that would trip up even veterans, and it's not helpful in understanding the basics of the language.Wellfound
@SilvioMayolo I see, I was reading C++ Primer and stumbled with this lesson. Thank you for the advice I'll take your word for it!Ellieellinger
@Ellieellinger Yeah, not your fault at all. There's a ton of bad beginner C++ advice out there, and sifting through it is incredibly difficult (trust me, we all had to go through that at one point). Good luck :)Wellfound
It's a bit baffling why a primer would jump in with decltype() so early. It's template engineering wizardry. Not for beginners.Phyllotaxis
R
18

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

Reply answered 23/8, 2022 at 13:12 Comment(0)
O
8

This code can be rewritten as:

int a = 3;  //Forget about b, it is unused

int c = a;  // copy (c is distinct from a)
int& d = a; // reference (a and d both refers to the same variable)

++c;
++d;

c is a distinct copy of a, incrementing it by 1 gives 4.

d is a reference of a (but still not related to c), incrementing it also give 4 (the only difference is that a is also modified since a and d both refers to the same variable).

Orderly answered 23/8, 2022 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.