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!
txt
is of typechar[100]
. It has to be converted to achar *
in order to be passed tofun
; 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:What would the following code do (assuming it could compile)?