🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4439

Re: giving a (*)(const void *) to a (*)(void *)

#4439
From: halvin
Date: Thu, 07 Dec 1995 20:43
56 lines
2075 bytes
Dominique.Marcadet@supelec.fr (Dominique Marcadet) writes:

>The following code compiles fine without any warning with the latest g++,
>but gcc emits a warning and other C compilers say it's an error.

>Is it really wrong according to the C standard ?

yes.

>extern void f (void (*) (void *));

>extern void g (const void *);

>void h ()
>{
>        f (&g);
>}

the rule that causes a 'T*' to be accepted in place of a 'T const*'
is only applied at the first level of indirection. e.g.:

    void* pv = 0;
    void const* pcv = pv;        /* okay */
    void const** ppcv = 0;
    void** ppv = ppcv;           /* not okay -- cast required */

this same principle is being applied to your example, above. it's similar to:

    int cmp1(void* p1, void* p2)
    {
        return strcmp(p1, p2);
    }
    int cmp2(void const* p1, void const* p2)
    {
        return strcmp(p2, p2);
    }
    qsort((void*)array, nelem, sizeof(array[0]), cmp1);   /* warning: cmp1 */
    qsort((void*)array, nelem, sizeof(array[0]), cmp2);   /* okay */

qsort expects a compare function that accepts pointers to CONST void.
the function cmp1() accepts pointers to void, which will not work, because
the fn parameters aren't const-qualified.

some would change that first example to this:

    qsort(.. , .. , .. , (int (*)(void const*, void const*))cmp1);

and this will probably work on most implementations, but it is not strictly
conforming. similarly, this:

    qsort(.. , .. , .. , (int (*)(void const*, void const*))strcmp);

is also not strictly conforming -- but fairly common nonetheless.

regards,
-mark
Technical Details
Message-ID: <4a7jkn$5g0@cmcl2.NYU.EDU>
Path: arc1-ca.pugleaf.net!news.sprintlink.net!rockyd!cmcl2!acf4!halvin
References: <Dominique.Marcadet-0712951751160001@marcadet.supelec.fr>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!news.sprintlink.net!rockyd!cmcl2!acf4!halvin
From: halvin@acf4.nyu.edu (halvin)
Newsgroups: comp.std.c
Subject: Re: giving a (*)(const void *) to a (*)(void *)
Date: 7 Dec 1995 20:43:03 GMT
Organization: New York University
Message-ID: <4a7jkn$5g0@cmcl2.NYU.EDU>
References: <Dominique.Marcadet-0712951751160001@marcadet.supelec.fr>
NNTP-Posting-Host: acf4.nyu.edu
X-Newsreader: NN version 6.5.0 #5 (NOV)