Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "const int& jj" and "int& const jj"?

I am confused with the two. I am aware of the C++ references which are inherently constant and once set they cannot be changed to refer to something else.

like image 386
username_4567 Avatar asked Sep 22 '16 06:09

username_4567


People also ask

What is the difference between int * const * const x?

int const * const x would be read as “x is a constant pointer to a constant integer”. You can’t change x to make it point to something else and you can’t change the data that x points to. const int * const x would be read as “x is a constant pointer to an integer that is constant”.

What is the difference between int&int and int&const?

Int &const is an invalid statement since const is a keyword. Int const& is also invalid as the reference operator is expecting a syntax of: datatype & variable name, in other words: this variable name is a reference to this data type. Const& int is also invalid for the same reason above: const is not a datatype.

What is the meaning of const int *const P ==>?

int *const p ==> p is read-only [ p is a constant pointer to an integer]. As pointer p here is read-only, the declaration and definition should be in same place. const int *p const ==> Wrong Statement. Compiler throws a syntax error. const int *const p ==> *p and p are read-only [ p is a constant pointer to a constant integer].

What is the use of int&and const in C++?

And const is used to make something constant. If there is int& constant, then it indicates that this will hold the reference of some int type data. This reference value is constant itself.


1 Answers

const int& means reference to const int. (Similarly, int& means reference to non-const int.)

int& const literally means const reference (to non-const int), which is invalid in C++, because reference itself can't be const-qualified.

$8.3.2/1 References [dcl.ref]

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name ([dcl.typedef], [temp.param]) or decltype-specifier ([dcl.type.simple]), in which case the cv-qualifiers are ignored.

As you said, references are inherently constant and once set they cannot be changed to refer to something else. (We can't rebind a reference after its initialization.) This implies reference is always "const", then const-qualified reference or const-unqualified reference might not make sense actually.

like image 50
songyuanyao Avatar answered Sep 28 '22 08:09

songyuanyao