www.digitalmars.com         C & C++   DMDScript  

D - const arguments

reply Axel Kittenberger <axel dtone.org> writes:
(was "Concrete Types/Argument Passing", I started it as new thread since it 
went off topic from the original, but is still interesting (at least for me 
:] ) )

Walter wrote:

 Even worse, const doesn't help the optimizer anyway, because some other
 non-const pointer may point to the same data and change it. Const just
 doesn't work as a type attribute.

Okay, I've yet never coded an optimizer, only the frontend parser/compiler. The fact it doesn't help the optimizer is because const casts are allowed after all, if they would be completly disallowed he might benefit from it, I just imagine sometimes if the programmer "betrays" the compiler it's his own fault. That's actually what 'volatile' is for in C or? Well take following C-code: (even without const) { int a = 2; int b = 4; *((&a) + 1) = 5; printf("b=%d\n"); } Now what will it print? Sure it's 4, the compiler does not really look what the contents of b actually are in the call to printf. Now what does this one do? { int a = 2; volatile int b = 4; *((&a) + 1) = 5; printf("b=%d\n"); } Those who know how the stack will look like know it will be 'b=5', so before we betrayed the compiler. Well I guess this example is not a must be, since how the compiler constructs the stack is completly his freedom, but with gcc on a x86 it works. And beside this code breaks of course a dozends of standards, so: kids don't try this at home :o) But what I understood you're generally favorising programming by contract or? So let's approach this maybe from a different angle, shouldn't there be a contract like: "I promise I will not change that"? This is that why people actually use 'const' in C and C++ functions. To give a contract what the implementer is allowed to do with it. The other purpose of const on embedded systems is target the section the code will end up. So in my eyes in C it are the same rules that try to cover actually to different goals. - Axel
Sep 07 2001
parent "Walter" <walter digitalmars.com> writes:
"Axel Kittenberger" <axel dtone.org> wrote in message
news:9nb2rp$1lqc$1 digitaldaemon.com...
 The other purpose of const on embedded systems is target the section the
 code will end up. So in my eyes in C it are the same rules that try to
 cover actually to different goals.

That's covered in D by making const an attribute of the storage, and not an attribute of the type. Another reason why const doesn't work with optimizers is the C rule that allows pointers to be implicitly converted to a const*. Now it looks like const to the type system, but really isn't. Believe me, I've tried to make this work. Too much code broke in obscure and bizarre ways.
Jan 04 2002