:: Re: [DNG] "Common knowledge?"-quest…
Pàgina inicial
Delete this message
Reply to this message
Autor: Rainer Weikusat
Data:  
A: dng
Assumpte: Re: [DNG] "Common knowledge?"-question
Didier Kryn <kryn@???> writes:
> Le 23/01/2016 19:28, Rainer Weikusat a écrit :
>> Didier Kryn <kryn@???> writes:
>>> Le 23/01/2016 12:16, Didier Kryn a écrit :
>>>>      I'm curious of the reason why you specify
>>>>     static void print_start(char const *name, char const *what)


[...]

>>>      Sorry, I overlooked the code and read "char const *name" as if it
>>> was "char * const name". Actually the syntax you used is equivalent to
>>> "const char *name".
>> That's a habit based on an observation I made when I started to write
>> code in C: Type qualifiers are left-associative (presumably a misuse of
>> the term) unless there's nothing to the left of them,


[...]

>     So, we could express it as the general declaration would be:


[...]

>     But another syntax is allowed, where the qualifier[s] can be on
> the left. I'm not sure there's a BNF description of the C syntax.


It's really

declaration:
       declaration-specifiers init-declarator-list[opt] ;


declaration-specifiers:
              storage-class-specifier declaration-specifiers[opt]
              type-specifier declaration-specifiers[opt]
              type-qualifier declaration-specifiers[opt]
              function-specifier declaration-specifiers[opt]


Which means a type-qualifier can appear both to the left and to the
right of a type specifier.

Originally (as I wrote) the fact that

const char *

meant 'pointer to constant char' while

char const *

also meant this and 'constant pointer to char' had to be expressed as

char * const

simply annoyed me because of it's irregularity --- but now, after having
had to deal with a somewhat largish Java codebase where absolutely
everything had a final tacked onto it, thereby making it seriously
difficult to spot the acting code among all the pointless declarational
clutter, I'm presumably in the process of stopping to use const
altogether.

>>> It actually protects the string from being overwritten by the
>>> function.
>> Not really. It just asserts that the string won't be modified using this
>> pointer. In theory, this would enable a compiler to optimize such
>> accesses, eg, collapse many of them into one, however, in practice, gcc
>> doesn't do that, and the qualifier is useless.
>
>     The most important goal is not to optimise the executable, it is
> to protect against programmer's errors. gcc will warn you if you try
> to modify a constant.


It won't even compile code trying to use a pointer-to-constant-something
to modify something. But this usually just means that the const ought to
be dropped. C is all about managing memory manually and this means
whenever the content of some (set of) memory location(s) is to be
modified, thought must be put into determining where this memory comes
from and which other code might use it in which way.