0

Trying to figure out why continued declaration is not a good Idea I suddenly realized the size assigned to following variables are not the same:

char const* const ALPHA, BETA;

printf("sizeof(ALPHA): %lu\n", sizeof(ALPHA));
printf("sizeof(BETA): %lu\n", sizeof(BETA));
printf("sizeof(char): %lu\n", sizeof(char));
printf("sizeof(char const* const): %lu\n", sizeof(char const *const));
printf("sizeof(char const*) %lu\n", sizeof(char const *));

output:

sizeof(ALPHA): 8
sizeof(BETA): 1
sizeof(char): 1
sizeof(char const* const): 8
sizeof(char const*) 8

Apparently BETA should be of type char const* not char const* const! but why it has the size of 1? is it really a char? How?

I expected that both variables be of the same size: 8

void
  • 7,760
  • 3
  • 25
  • 43
  • 5
    The good ole "to what does the asterisk belong" confusion. Your BETA is really just a char. – Marcus Müller Dec 29 '22 at 00:35
  • 5
    I think you found out why these sorts of declarations can be trouble. – tadman Dec 29 '22 at 00:35
  • Was about to write what @tadman wrote. Thanks for illustrating so nicely why these continued declarations probably weren't the best language features of C. – Marcus Müller Dec 29 '22 at 00:37
  • so BETA is really just a char and not a const pointer to a char nor a const pointer to a const char! :-) – void Dec 29 '22 at 00:41
  • 3
    C is really, *really* weird in how the declarations work, enough so that there's actually a [decoder site](https://cdecl.org) if things get too dizzying to puzzle through yourself. Declaring things on separate lines isn't a bad idea, it reminds you to *properly initialize* them! – tadman Dec 29 '22 at 00:43
  • @tadman even that doesn't deal with multiple declarations. – Marcus Müller Dec 29 '22 at 00:44
  • 1
    @tadman, the site you mentioned is really great and helpful, thank you a lot. – void Dec 29 '22 at 00:45
  • @MarcusMüller I tried the example and it gave up, which is never a good sign. That's surely a popular feature request, though! – tadman Dec 29 '22 at 00:45
  • I'd say it may be a duplicate of https://stackoverflow.com/questions/70035094/pointer-declaration-c-standard , if only that Standard quote was meant for human consumption. https://stackoverflow.com/questions/6990726/correct-way-of-declaring-pointer-variables-in-c-c is probably better. – Bob__ Dec 29 '22 at 00:51
  • 1
    Sidenote: `%lu` is not the proper conversion specifier for `sizeof`. Use `%zu`. – Ted Lyngmo Dec 29 '22 at 00:55
  • 1
    On the question: You can always do `typedef char const* const very_const_ptr;` and then `very_const_ptr ALPHA, BETA;` to get both to be of the same type - but, prefer to declare them separately instead. – Ted Lyngmo Dec 29 '22 at 00:58

0 Answers0