Const keyword in function with an *& argument.

76 views Asked by At

can you please explain why in the following code:

    #include <iostream>
    void fun(char * const & x){(*x)++;}
    int main(){ 
        char txt[100]="kolokwium";  
        fun(txt);
        std::cout << txt <<"\n";
    }

keyword const is needed for code to compile?

If I remove it I get:

 invalid initialization of non-const reference of type ‘char*&’ from an rvalue of type ‘char*’

thanks!

1

There are 1 answers

3
Oliver Charlesworth On BEST ANSWER

txt is of type char[100]. It has to be converted to a char * in order to be passed to fun; this conversion produces an rvalue. You cannot create a non-const reference from an rvalue.

To illustrate, consider what would happen if fun were defined as follows:

void fun(char *&x) { x++; }

What would the following code do (assuming it could compile)?

char txt[100]="kolokwium";
fun(txt);                      // Huh?