What does {int &x;} means | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

What does {int &x;} means

I think it should be different from both &x and int *x.

11th Aug 2017, 3:11 AM
Edward Ji
Edward Ji - avatar
2 ответов
+ 4
idk what's with the curly braces, but if you have: int a = 2; int &b = a; now b is a. Not just equal to a, but b is a itself. If you make b++, now a is 3! We say that b is a reference to a. If you have: int *pa = &a; here pa is a pointer, and &a is 'address of a'. To access a through pa you can do: *pa = 9; and now a is 9. Now, if you have: void func(int &x) { x = 7; } and you call func(a), now a is 7. We say that the parameter to func() is passed by reference. Btw, such a function can only be called with l-value variables as parameters, never with imediate or const values, I think. You can't call func(2) for example. If you had void funcp(int *px) { *px = 6; } and call funcp(&a); // see, you have to give the 'address of a' as argument! now a is 6.
11th Aug 2017, 3:57 AM
lion
lion - avatar
+ 10
You are creating a reference variable with the former, and a pointer with the latter. A reference variable is simply an alias to the variable it references. (i.e. Another name for the variable assigned to it). A pointer variable is a variable which stores the address of another variable.
11th Aug 2017, 5:05 AM
Hatsy Rei
Hatsy Rei - avatar