Joeytje50 Joeytje50 - 20 days ago 7
C++ Question

Why can I not define two pointers at once?

I've got some code that did not work, where the solution was very simple: simply writing it all in a longer way. Namely, the following:

I know that the following is correct code:

int main() {
int a = 1,
b = 2;
return 0;
}


But I was surprised to see that the following gives an error:

struct Foo {
int a = 0;
};


int main() {
Foo* f = new Foo;
Foo* x = f,
y = f;
return 0;
}


This gives the following error:

error: conversion from ‘Foo*’ to non-scalar type ‘Foo’ requested
y = f;
^


Even though it would work if you'd replace the definition of
x
and
y
with:

Foo* x = f;
Foo* y = f;


So could someone explain why this is not allowed (or redirect me to the inevitable other SO question that explains this, which I could not find by this error)?

Answer

This is why the common C++ style of writing Foo* x, instead of Foo *x as is preferred style in C, is wrong wrong wrong.

Unary * acts on the thing to its right, not on the thing to its left. Your

Foo* x = f,
     y = f;

means the same as

Foo *x = f;
Foo y = f;

If you want to stick to the shorthand, you have to write an asterisk for each variable you're declaring:

Foo *x = f,
    *y = f;

Modifiers like const are the opposite; they modify the thing to their left.

Foo const x, y;

is the same as

Foo const x;
Foo const y;

But watch out for

Foo *const x,
    *y;

where x is a const pointer to non-const Foo and y is a non-const pointer again to non-const Foo.

(Nowadays in both C and C++, the preferred style is to write only one variable declaration per semicolon, and that really is a lot less confusing. I will occasionally still write int i, j, k; but only when it's that simple.)

Comments