2020-05-04

Why swapp(pa, pb); works but swapp(&a, &b) is wrong in C++? (swapp is a function)





#include <iostream>
void swapp(const int*& rpa, const int*& rpb) {
        const int* temp = rpa;
        rpa = rpb;
        rpb = temp;
}
int main(void) {
        const int a = 33;
        const int b = 99;
        const int* pa = &a;
        const int* pb = &b;

        swapp(pa, pb);
        swapp(&a, &b);//This is wrong

        return 0;
}


Now pa is the same as &a
Why swapp(pa, pb); works but swapp(&a, &b) is wrong?

1 comment:

Unknown said...

The function accepts two references to a non-constant pointer to a constant integer. pa and pb are lvalues (legitimate assignment targets ... i.e. there is a place in memory where they are). &a and &b (unless assigned to a variable/constant) are RVALUES and rvalues cannot be modified. Hence, when not stored in a pointer variable ... when rvalues, their type is not non-constant pointer to constant integer but constant pointer to constant integer (i.e. const T* const, NOT const T*).

It may help to think of a slightly different function:

void swap(int& l, int& r)
{
int temp = r;
r = l;
l = temp;
}

callsite:
int x = 9;
int y = 10;
swap(x, y); //WORKS
swap(9, 10); //WRONG

The second is basically what you are attempting to do with swapp(&a, &b);

Rvalues, be they memory addresses (&x, &y) or integers (9, 10) are always const .... you can't write to them. The parameters accepted (by reference) in your function are "const T*&" which is (reference to) NON-CONTANT POINTER (i.e. mutable) to CONSTANT INTEGER. I.e. the pointer's value is mutable but the pointer cannot be used to change the value of the pointee. &a, when used like this evaluates to CONSTANT POINTER TO CONSTANT INTEGER (you can neither change the value of the pointer itself nor the value of the thing it points to by using it).

For a function to accept rvalue &a or rvalue &b by reference, the function parameter would need to read "const int* const& rab". Of course, a function that accepts such parameters cannot write to them and thus cannot be used to "swap".

How to Add a Directory to PATH in Linux

 https://linuxize.com/post/how-to-add-directory-to-path-in-linux/ When you type a command on the command line, you’re basically telling the ...