Re: Function pointer question P119 K&R
- From: mdh <mdeh@xxxxxxxxxxx>
- Date: Wed, 9 Jul 2008 21:55:23 -0700 (PDT)
On Jul 9, 9:26 pm, Barry Schwarz <schwa...@xxxxxxxx> wrote:
On Wed, 9 Jul 2008 20:23:18 -0700 (PDT), mdh <m...@xxxxxxxxxxx> wrote:
On Jul 8, 10:22 pm, Richard Heathfield <r...@xxxxxxxxxxxxxxx> wrote:
m said:
<snip>
Ben, you say that void * and char * must have the same size and
representation. Are you saying that this is a fact in C,
Buried deep in 3.1.2.5 we find that "A pointer to void shall have the same
representation and alignment requirements as a pointer to a character
type. Other pointer types need not have the same representation or
alignment requirements."
Not to flog a dead horse, does this then mean that when a void pointer
is passed to function (foo) expecting a character pointer, foo simply
cannot tell the difference between what it is expecting and what it is
getting, or that the compiler does not complain as **it** knows that
there is no difference between the two and thus allows this step to
occur without any warning?
There is a difference between the function knowing what to expect and
the compiler knowing what the function expects. If the prototype
tells the compiler the function is expecting a non-void object
pointer, then any void* whose value is properly aligned for the object
type will be converted automatically. Similarly, if the compiler
knows that the function is expecting a void*, then any object pointer
will be converted automatically. This is a result only of the
implicit conversion between void* and object pointer and has nothing
to do with the mandatory similarity between void* and char*.
On the other hand, consider the case of a variadic function like
printf. When processing a %p format specification, the function
expects a void*. However, the compiler has no idea and will pass a
char* without modification. (Before someone notes that some compilers
do in fact check the format string, I remind them that the format
string need not be a literal and the compiler may not know it's
contents.) In the unlikely event that there is a different passing
mechanism for void* and char*, you have undefined behavior in spite of
the mandatory similarity between the two.
Remove del for email
Barry, thank you for that erudite explanation. It really adds to my
understanding of C.
.
- References:
- Function pointer question P119 K&R
- From: mdh
- Re: Function pointer question P119 K&R
- From: Ben Bacarisse
- Re: Function pointer question P119 K&R
- From: m
- Re: Function pointer question P119 K&R
- From: Richard Heathfield
- Re: Function pointer question P119 K&R
- From: mdh
- Re: Function pointer question P119 K&R
- From: Barry Schwarz
- Function pointer question P119 K&R
- Prev by Date: Re: Function pointer question P119 K&R
- Next by Date: Re: Problem 77: Greedy Gift Givers
- Previous by thread: Re: Function pointer question P119 K&R
- Next by thread: Re: Function pointer question P119 K&R
- Index(es):
Relevant Pages
|