in #c
Which of the examples below are preferable?
char* name; char *name;
As an inexperienced C programmer, the first example made more sense to me. The * signifies that this is a pointer. A pointer to a char. I saw it as part of the type.
But most C code that I have seen seems to prefer the second example. So does the linux kernel coding style:
When declaring pointer data or a function that returns a pointer type, the preferred use of * is adjacent to the data name or function name and not adjacent to the type name. Examples:
char *linux_banner; unsigned long long memparse(char *ptr, char **retptr); char *match_strdup(substring_t *s);
I have found an example that changes my opinion:
#include <stdio.h> int main(void) { char* a, b; printf("sizeof(a) = %d\n", sizeof(a)); printf("sizeof(char*) = %d\n", sizeof(char*)); printf("sizeof(b) = %d\n", sizeof(b)); printf("sizeof(char) = %d\n", sizeof(char)); return 0; }
On my machine, it prints this:
sizeof(a) = 8 sizeof(char*) = 8 sizeof(b) = 1 sizeof(char) = 1
With my previously preferred syntax, you would think that b is a pointer to a char. Indeed, I also thought that it was in this example. But apparently, that is not how C parses
char* a, b;
In order for both a and b to be pointers, you have to write
char *a, *b;
And now I'm convinced that it is better to put the star adjacent to the variable name. I'm not sure that I can make the same argument about putting the star adjacant to function names that return pointers. However, it makes sense to use the same convention in both cases.
I will go over my code and move all stars.
What is Rickard working on and thinking about right now?
Every month I write a newsletter about just that. You will get updates about my current projects and thoughts about programming, and also get a chance to hit reply and interact with me. Subscribe to it below.