On Mon, Sep 17, 2012 at 2:34 PM, Jakub Jermar <[email protected]> wrote:
> Hi Jano,
>
> thanks for producing the initial material for the heated debate :-)
> Speaking for myself, I think some clarifications are needed, please see
> below.

thx for reading it :)

>
> On 10.9.2012 18:38, Ján Veselý wrote:
>> Using pointers is a bit different. It still makes no sense to declare 
>> pointer parameters constant, but USING POINTERS TO CONST DATA IS OF GREAT 
>> USE. Example:
>>
>> int count_something(const struct foo_t *instance);
>>
>> const struct foo_t *my_foo = get_foo();
>> const int something_count = count_something(my_foo);
>>
>> If the data in foo_t changed after a call to this function it's a bug 
>> (memory corruption, ...).
>
> What if count_something() casts the instance variable to a (struct foo_t
> *) pointer and uses that pointer to modify the data? Is such a cast
> allowed? C99 in 6.7.3 (5) says that:
>
>  If an attempt is made to modify an object defined with a const-
>  qualified type through use of an lvalue with non-const-qualified type,
>  the behavior is undefined.

That is the point. If a function takes const type * as an argument, it
indicates that it does not modify the instance. (and non-const args
imply that the function in one if its paths DOES modify the instance)
We can't prevent programmer from using explicit casts to remove
constness, but such casts are easy to spot/grep. i.e. the rule is
"don't cast, make up your mind whether you need writable instance or
not and declare parameter's qualifier accordingly".

Sidenote: Ideally, there should be no explicit pointer casts. Casts
to/from void* are implicit and we should not use any other pointer
cast. (there are of course exceptions like getting list instance...)

>
> What if count_something() can get the address returned by get_foo() from
> elsewhere?

I'm not sure I understand. count_something() does not care where the
pointer is from. It states that it works on RO instance. If you have a
pointer to RW instance it will be implicitly cast to pointer to RO
instance (that is perfectly OK). In the example it even does not
matter whether get_foo() returns pointer to RO or RW instance.

jan


>
> Jakub
>
> _______________________________________________
> HelenOS-devel mailing list
> [email protected]
> http://lists.modry.cz/cgi-bin/listinfo/helenos-devel

_______________________________________________
HelenOS-devel mailing list
[email protected]
http://lists.modry.cz/cgi-bin/listinfo/helenos-devel

Reply via email to