tags:

views:

287

answers:

4

Is there a difference between the following declarations?

void somefunc(const Person &p);
void somefunc(Person const &p);
+14  A: 

there is no difference. const binds to the type to its left...unless it is the first part of the declaration in which case it binds to the right.

See: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.8

Personally, I find that const T &x reads better. According to this, Bjarne also prefers to put the const first. Specifically because the keyword was originally going to be called readonly and readonly int x reads better :-P.

Evan Teran
Though I would say the first is more common.
rlbond
@rlbond: More common depends on a context. In certain places I see the first more common in others I see the second more common. It all depnds.
Martin York
certainly the second is more *consistant* when dealing with indirection. for example: int const *const x; (everything binds left)
Evan Teran
+3  A: 

See this link

Specifically 18.6 to 18.8.

[18.6] What does "const Fred& x" mean?

It means x aliases a Fred object, but x can't be used to change that Fred object.

[18.7] Does "Fred& const x" make any sense?

No, it is nonsense.

[18.8] What does "Fred const& x" mean?

Fred const& x is functionally equivalent to const Fred& x. However, the real question is which should be used.

Read the rest of the article for more info. But essentially, it says they are equivalent, and you can use either one as you see fit. However, you should pick one and stick with it, to avoid future confusion.

abelenky
I'll add, pick one and stick with it when writing new code, but when modifying existing code, stick with the way the existing code does it.
Rob K
+9  A: 

Yes there is! the first one is more readable :)

AraK
+1 Simply because it made me chuckle, and others are sure to downvote. :P
GMan
A difference means any difference right ? :)
AraK
I'll upvote, made me giggle
Carson Myers
i guess you want to say "more readable to the ones that read LTR!" :) i heard some folks in the eastern read their text RTL.
Johannes Schaub - litb
No! The second! (Really - you have to read definitions right-to-left: Person const* volatile* p; // p is a volatile pinter to a cont pointer to a Person. )
MSalters
@litb :: I read one of those RTL languages and it is not hard because it is my native language :D
AraK
A: 

It really is a matter of taste.

If read from right to left, "Person const & x" reads "x is a reference to a constant Person."

This sounds better than "const Person & x", which would be "x is a reference to a Person, which is constant."

So if one is familiar with the right-to-left reading direction of variable declarations, one perhaps would prefer the first one.

DHReutter