I am using gcc 4.8.1 and I am unable to understand output of following program.
#include<stdio.h>
int main()
{
char* a, b, c;
int* d, e, f;
float* g, h, i;
printf("Size of a %zu and b %zu and c %zu \n", sizeof(a), sizeof(b), sizeof(c));
printf("Size of d %zu and e %zu and f %zu and int is %zu \n", sizeof(d), sizeof(e), sizeof(f), sizeof(int*));
printf("Size of g %zu and h %zu and i %zu and float is %zu \n", sizeof(g), sizeof(h), sizeof(i), sizeof(float));
return 0;
}
Size of a 4 and b 1 and c 1
Size of d 4 and e 4 and f 4 and int is 4
Size of g 4 and h 4 and i 4 and float is 4
My question is why b and c are not char* type whereas same is possible in case of int and float. I want to know about how C grammar splits declarations.
In a declaration like
char* a, b, c;
Only the type char is used for all variables, not whether it is a pointer (* symbol). When used like that this (equivalent) syntax makes it more clear:
char *a, b, c;
To define 3 pointers:
char *a, *b, *c;
Or in cases where multiple pointers to char are often used, maybe do a typedef:
typedef char* char_buffer;
char_buffer a, b, c;
The problem is that you are using a bad style of declarations
These declarations
char* a, b, c;
int* d, e, f;
float* g, h, i;
are equivalent to
char* a;
char b, c;
int* d;
int e, f;
float* g;
float h, i;
sizeof an object of type char is equal to 1 while sizeof( char * ) in your system is equal to 4. So you get correct output
Size of a 4 and b 1 and c 1
As sizeof( int ) and sizeof( float ) in your system is equal to 4 then you get output
Size of d 4 and e 4 and f 4 and int is 4
Size of g 4 and h 4 and i 4 and float is 4
I said that you use bad style of programming because the declarations you are using like this
char* a, b, c;
do not consistent with the C grammar. The C grammar splits declarations in declaration specifiers (for the statement above it is keyword char) and declarators (in statement above they are *a, b, and c ). So you should follow the C grammar. In this case your code will be more clear.
char *a, b, c;
(Compare for example
char unsigned* c;
and
char unsigned *c;
What declaration is more clear?)
Do not forget that your code can read programmers that for example do not know C but know C#. In this case they will be simply confused. They will consider the declarations in the wrong way as you considered them in your post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With