Where to put a star in the designation of a pointer to C and C ++

Possible duplicate:
The correct way to declare pointer variables in C / C ++

For some time, the following annoyed me: where should I put the star in a notation with a pointer.

int *var; // 1 

and

 int* var; // 2 

obviously do the same thing, and both entries are correct, but I find that most of the literature and code I'm looking at uses the 1st notation.

Wouldnโ€™t it be more โ€œcorrectโ€ to use the 2nd notation, separating the type and name of the variable with a space, and not mixing the type and variable markers?

+20
c ++ c
Dec 15 '12 at 16:59
source share
3 answers

No. Never. <g>

But consider:

 int* var1, var2; 

Here the placement * is misleading, since it does not apply to var2 , which is int , not int* .

+20
Dec 15 '12 at 17:00
source share
โ€” -

Linux kernel coding style convention:

 int *ptr1 , *ptr2; 

Therefore, I think you should accept this as an agreement.

When declaring data of a pointer or function that returns a type of pointer, the preferred use of * is next to the data name or function name, and not next to the type name. Examples:

 char *linux_banner; unsigned long long memparse(char *ptr, char **retptr); char *match_strdup(substring_t *s); 
+13
Dec 15 '12 at 17:03
source share

I believe that part of the reason for this notation is that the use and declaration of a variable looks the same.

 int *var; int x; x = *var; 

You can also think of it as dereferencing var give you an int.

+9
Dec 15 '12 at 17:01
source share



All Articles