Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.std.c > #6572

Re: why can change element of a const typed struct ?

From Ben Bacarisse <ben.usenet@bsb.me.uk>
Newsgroups comp.std.c
Subject Re: why can change element of a const typed struct ?
Followup-To comp.lang.c
Date 2023-09-18 20:13 +0100
Organization A noiseless patient Spider
Message-ID <87cyyfjnvl.fsf@bsb.me.uk> (permalink)
References <6d826a46-8852-4aa3-9e7d-23fac761e840n@googlegroups.com>

Followups directed to: comp.lang.c

Show all headers | View raw


Denis Dos Santos Silva <denis@roo.com.br> writes:

> hi all!

This would probably be better sent to comp.lang.c so I am setting the
followup-to header accordingly.  This group is mainly about the ISO C
standard, though it's possible you are asking why the standard permits
this.

> why this works? =)
(from subject) why can change element of a const typed struct ?

Short answer: you are not changing any member of the struct.  The
constness of the target of the pointer does transfer to other pointers
in the struct.  data is const, but data[x] is not.

A detail...  the struct is not const (well, it might be, but we can't
tell from this code).  The struct is being accessed via pointer whose
target type is const.  Now that would indeed require a diagnostic if the
code tried to change any of the members, but it does not.

> /// image.c 
> /// ...
> typedef struct {
> 	int w;
> 	int h;
> 	unsigned char channels;
> 	unsigned char *data;
> 	int err;
> } image_t;
>
> int image_copy(const image_t* source, const image_t* target, int
> xoffset, int yoffset) {
...
> 			source->data[sindex+0] = target->data[tindex++];
> 			source->data[sindex+1] = target->data[tindex++];
> 			source->data[sindex+2] = target->data[tindex++];
...
> }
> /// <eof>

-- 
Ben.

Back to comp.std.c | Previous | NextPrevious in thread | Find similar


Thread

why can change element of a const typed struct ? Denis Dos Santos Silva <denis@roo.com.br> - 2023-09-18 08:49 -0700
  Re: why can change element of a const typed struct ? David Brown <david.brown@hesbynett.no> - 2023-09-18 20:29 +0200
    Re: why can change element of a const typed struct ? Ben Bacarisse <ben.usenet@bsb.me.uk> - 2023-09-18 20:58 +0100
      Re: why can change element of a const typed struct ? David Brown <david.brown@hesbynett.no> - 2023-09-19 17:15 +0200
  Re: why can change element of a const typed struct ? Ben Bacarisse <ben.usenet@bsb.me.uk> - 2023-09-18 20:13 +0100

csiph-web