const religion

John E. Malmberg wb8tyw at qsl.net
Thu Mar 31 03:05:10 GMT 2005


Andrew Bartlett wrote:
> On Wed, 2005-03-30 at 16:31 -0600, Gerald (Jerry) Carter wrote:
> 
>>-----BEGIN PGP SIGNED MESSAGE-----
>>Hash: SHA1
>>
>>I agree here. I argued this same point when the const religion
>>got started.  const in C is a joke IMO.  The compiler
>>doesn't really mark the memory as read-only so you just as well
>>off to put the const keyword in the comments for the function
>>formal declaration.  Then at least you don't get the silly
>>warnings about something you know you already did.
>>
>>But I digress....

The const qualifier is an important clue to the compiler optimizer, 
particularly on CPUs with lots of registers.

When a prototype tells the compiler that a pointer is a "const", the 
compiler knows that all the registers that were previously loaded in by 
values from the item pointed to are still valid after the routine 
completes.  With out the const qualifier, they need to be reloaded.

Since the compiler knows that the values are not changed, it can also 
move some calculations around the routine call to optimize it's use of 
registers.

> const and formal correctness is a hot-button issue for some - I simply
> see it simply as an extra tool to be used as far as reality allows, to
> try and catch silly bugs.

Depending on the CPU and the quality of your compiler, the use of 
"const" can make a significant impact on the size and the speed of the 
machine code generated.

One of the other practices that hurts optimizations is to have external 
functions that are slightly modified wrappers for standard routines that 
the compiler knows how to inline.  A macro or a "static" function in a 
header file will get the same job done, yet allow the compiler optimizer 
to do it's job.

Many of the string and memory functions can be inlined this way, or 
invoked with lower overhead calling convention than user written 
external routines.

-John
wb8tyw at qsl.network
Personal Opinion Only



More information about the samba-technical mailing list