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


Groups > comp.std.c > #6573

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 ?
Date 2023-09-18 20:58 +0100
Organization A noiseless patient Spider
Message-ID <871qevjls3.fsf@bsb.me.uk> (permalink)
References <6d826a46-8852-4aa3-9e7d-23fac761e840n@googlegroups.com> <uea4ti$1stu4$1@dont-email.me>

Show all headers | View raw


David Brown <david.brown@hesbynett.no> writes:

> On 18/09/2023 17:49, Denis Dos Santos Silva wrote:
>> hi all!
>> why this works? =)
>
> Your image_t is const, but it has a non-const pointer "data" - there is no
> restriction to accessing the elements pointed to by source->data.

I feel I must quibble because it can matter to someone learning C.

When accessed via 'const image_t *source', data /is/ (treated as) const.
data is a pointer, and the lvalue expression source->data is const
qualified.  To call it a "non-const pointer" is using a common
shorthand, but one I've found is very confusing to beginners.

We casually talk about "const pointers" and "non-const pointers" because
we all know what we mean, but people learning C can get confused by what
is and is not const-qualified.  It's a handy shorthand because an actual
'const pointer' is not seen so often:

  char *const endp = start + strlen(start);

But we often see this

  const char *end = start + strlen(start);

described as a const pointer even though changing the pointer is
perfectly valid:

  end -= 1;  // permitted because end is pointer that is not const

> So your function can't change "source->data",

Right, because data is treated as a const pointer.  Calling it a
non-const pointer is potentially confusing.  I know what you meant, but
is it clear to everyone?

> but it /can/ change "source->data[sindex]".
>
> "const" does not pass through layers of pointers, it only applies to the
> first pointed-at layer.

Your remark suggests that there is something special about one level of
indirection, but there isn't.

-- 
Ben.

Back to comp.std.c | Previous | NextPrevious in thread | Next 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