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

Time:08-24

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.

CodePudding user response:

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

CodePudding user response:

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).

  • Related