2020-05-08

Why does a reference formal parameter fail to be changed in a C++ function?



#include <iostream>
int summ(const int(&ra)[4]) {
        int sum = 0;
        const int* const end = ra + 4;

        while (ra != end)
                sum += *ra++;//wrong

        std::cout << *ra << std::endl;//ok

        return sum;
}

int main(void) {
        int a[4] = { 1,2,4,5 };

        std::cout << summ(a) << std::endl;

        return 0;
}
  
 a is pointer to array of 4 of integers

 ra is reference to a 

 It means when ra changes, a changes also

 so std::cout << *ra << std::endl;//ok  works.

  But I haven't set ra to be const reference

 Why does an attempt to change value of ra in sum += *ra++; fail to work?

You may wonder why I asked this.

Because in one other situation, reference as a formal parameter can be altered.

Like the following in which rpa can be altered to 0.

#include <iostream>
void test(const int*& rpa) {
        rpa = 0;
        std::cout << rpa << std::endl;
}

int main(void) {
        int a = 1;
        const int* pa = &a;

        test(pa);

        return 0;
}

































No comments:

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