views:

55

answers:

3

Possible Duplicates:
Declaring pointers; asterisk on the left or right of the space between the type and name?
what is the difference between const int*, const int * const, int const *

I've been wondering what is the difference between:

float const &var
const float &var

And which one of these is the correct way of writing the code? (including the above example):

float const& var
float const &var
float const & var

and with pointers:

float * var
float *var
float* var

I always put the special marks just before the variable name, feels most logical. Is that the correct way ?

A: 

Regarding your first question: Refer this: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.8

const X& x and X const& x are equivalent.

When it comes to pointers:

float *var

is the best way.

The reason is that it doesn't give a wrong impression when you have multiple pointer variables.

For example:

float *var, *foo, *bar;

Is correct if you are wanting 3 pointer variables.

Compared to the possibly wrong code:

float* var, foo, bar;
bits
I say stop pointing multiple declarations on the same line. Or know what you're doing if you do.
GMan
You can have your cake and eat it with `float* var,* foo,* bar;` :)
brone
Well, we can have holy wars on personal preferences on coding style. It was just my take. Thanks for your inputs.
bits
_we can have holy wars on personal preferences..._ Not on Stack Overflow, we won't.
James McNellis
+2  A: 

All are equally valid. There is no one correct way; you should do whichever you find most readable (for your own code) or follow the prevailing style (if working with others).

Putting const first (e.g., const float & rather than float const &) is more common in my experience.

The positioning of & and * depends on programmer; no choice seems more common than any other, in my experience.

brone
A: 

The first code snippet you exposed reminds of the const correctness: http://en.wikipedia.org/wiki/Const-correctness#C.2B.2B_syntax. In the other two code snippets any of variants have the same effect. For further information about pointers and the const keyword read also the following piece of documentation: http://www.cplusplus.com/doc/tutorial/pointers/

John Paul