silverwolf silverwolf - 1 year ago 112
C++ Question

C++ Primer exercise 2.27 [5th ed.]

I am doing exercise 2.27 from C++ primer 5th edition and I am confused in this question:

Exercise: Which of the following initializations are legal? Explain why.

(c) const int i = -1, &r = 0;

I came to conclusion that r is illegal because this will be same as below:

const int i = -1;
int &r = 0;

But this github repo suggest that (c) is same as below:

const int i = -1;
const int &r = 0;

So, it contradicts to my answer, please provide me the correct answer.

P.S.: I am begineer in C++ language.

Answer Source

The type specifier (int) with the qualifier (const) belong to all declarators in the declaration

const int i = -1, &r = 0;

Thus declarators i and &r have the type specifier and qualifier const int. Moreover you may not write for example

int &r = 0;

because a temporary object (in this case expression 0) may not be bound to a non-constant reference.

However you could write

int &&r = 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download