Can func(const T) be cast to func(T)?

Can func(const T) be cast to func(T)?

Post by Frederic B » Tue, 14 Dec 2004 04:18:27


In short, is this allowed:

int foo(const *int x) {
...
}

int(*bar)(*int) = foo;


It would certainly make sense to me, since any call to an int(*)(*int)
could easily be replaced with a call to an int(*)(const *int) w/o any
problem. However, I don't know if C99 requires T and const T to have
the same representation, which would be necessary for this to work.
(All I have for reference is K&R, and const was almost an afterthought
to them.)


--
Fric Brie <*> XXXX@XXXXX.COM

=> < XXXX@XXXXX.COM > IS NO MORE: < http://www.yqcomputer.com/ > <=
 
 
 

Can func(const T) be cast to func(T)?

Post by Wojtek Ler » Tue, 14 Dec 2004 06:19:15


In short, no, even if you meant

int (*bar)(int*) = foo;

The two function types involved are incompatible, and initialization of a
pointer to function requires a compatible type.

You can use a typecast to make the initialization valid:

int (*bar)(int*) = (int (*)(int*)) foo;

but it's less clear whether an attempt to use bar to call foo is guaranteed
to work. On the one hand, pointers to int and pointers to const int are
indeed guaranteed to have the same representation and alignment
requirements, and a footnote in the standard explains that those
requirements "are meant to imply interchangeability as arguments to
functions" (among other things). On the other hand, footnotes are not
normative, and the normative text of the standard fails to make the
guarantee that the footnote describes. For instance, imagine a compiler
that uses different registers to pass a pointer argument depending on
whether the parameter was declared as pointing to a const-qualified type or
not. Except for the footnote, there's no text in the standard that such a
compiler would violate.

 
 
 

Can func(const T) be cast to func(T)?

Post by Jun Woon » Tue, 14 Dec 2004 11:02:00


[...]

Until the standard says int and const int *are* compatible in type
system beyond saying that they have the same representation/alignment
restirction and can be used interchangeably, it's not guaranteed that
one can call a function whose parameter type is const int through a
pointer to function whose parameter type is int because we have an
explicit wording saying undefined behavior about it.


I believe we should be as particular as possible over this.
Admittedly, C99 made progress to fulfill the informative footnote but
I think it's not complete yet. Though, if the standard says in the
normative text that T is not allowed while T' is, when T and T' share
the same representation, it should be understood as written until the
committee decides to modify the normative part.
 
 
 

Can func(const T) be cast to func(T)?

Post by Douglas A. » Tue, 14 Dec 2004 16:00:49


Neither line is valid C.