reference variable

后端 未结 3 1123
感情败类
感情败类 2021-01-19 16:13

In some text it is given that we can\'t assign constant values to a reference variable. When I executed such a program I could do it. Is there any condition we can\'t assign

3条回答
  •  被撕碎了的回忆
    2021-01-19 16:51

    You can initialize a constant reference to a constant value.

    const int &i = 12;
    

    If the reference is not const, you get a compiler error.

    int &i = 12; //compiler error
    

    Constant values (e.g. literals) are (most of the time) stored in read-only segments of the memory. Consequently, you can't reference them using non-const references, because that would mean you could modify them.

提交回复
热议问题