"Simon Biber" <> wrote in message news:<3f7d8e5d$0$26924$. au>...
> "herrcho" <> wrote:
> > int intcmp(const void *a, const void *b)
> > {
> > return (*(int*)a - *(int*)b);
> > }
> >
> > in the above , if i put just 'void' instead of 'const void' as a
> > parameter,
> >
> > what's the difference ?
>
> If you're intending to pass this function to qsort or something
> that expects a parameter of type int(*)(const void*,const void*)
> then you must not change from const void to void, this will be
> a constraint violation (wrong type of argument) or else undefined
> behaviour (if you say cast it back to the right type).
>
> > i can't get the meaning of const when used in parameter..
>
> When used as 'const type *a' it means that you are not allowed to
> modify the thing that the pointer is pointing to. Unfortunately
> due to the bad way you wrote the function this protection is lost
> when you cast the argument to (int*). You can in fact write any
> qsort compare function in a completely typesafe manner with no
> casts, which is much cleaner code:
>
> int intcmp(const void *va, const void *vb)
> {
> const int *a = va, *b = vb;
> return *a - *b;
> }
>
Friends,
Don't we have to cast a void* so that the void points to a valid
value (as per 6.3.2.3 of the standard). (Correct me if I am wrong):
int fun(const void *a, const void *b)
{
unsigned int *p , *q;
p =(unsigned int*) a, q =(unsigned int*) b;
/*return (*p > *q ) - (*p < *q); */
return *p - *q;
}
int main(void)
{
int a=2,b=2,c=8,d=6;
printf("%d %d\n",fun(&a,&b),fun(&c,&d));
return 0;
}
OUTPUT:
0 2
And for the second one:
int fun(const void *a, const void *b)
{
unsigned int *p , *q;
p =(unsigned int*) a, q =(unsigned int*) b;
return (*p > *q ) - (*p < *q);
/*return *p - *q; */
}
int main(void)
{
int a=2,b=2,c=8,d=6;
printf("%d %d\n",fun(&a,&b),fun(&c,&d));
return 0;
}
OUTPUT:
0 1
Is there any UB?
> That way you will get a diagnostic message from the compiler if
> you accidentally attempt to modify the contents of the memory.
|