Same pointer parameter const and non-const

Same pointer parameter const and non-const

Post by Old Wol » Wed, 04 Nov 2009 09:56:56


Is this program guaranteed to print 10, or can the compiler
get 'confused' by the const and assume the variable
still has its initial value?

#include <stdio.h>

int func(int *A, int const *B)
{
*A = 10;
return *B;
}

int main()
{
int X = 5;
printf("%d\n", func(&X, &X));
}
 
 
 

Same pointer parameter const and non-const

Post by Seeb » Wed, 04 Nov 2009 10:01:56


I would say it has to print 10. There's no restrict anywhere in sight,
there's questionable aliasing, so I think the compiler's obliged to
assume that modifications of other objects with compatible types could
potentially modify the thing pointed to by B.

-s
--
Copyright 2009, all wrongs reversed. Peter Seebach / XXXX@XXXXX.COM
http://www.yqcomputer.com/ ;-- lawsuits, religion, and funny pictures
http://www.yqcomputer.com/ (Scientology) <-- get educated!

 
 
 

Same pointer parameter const and non-const

Post by DanDanDa » Thu, 05 Nov 2009 17:27:36


The const will only mean that func won't set B, it won't assume anything
else. The compiler won't get confused either, it will optimise away that
shit completely.
 
 
 

Same pointer parameter const and non-const

Post by Ben Bacari » Thu, 05 Nov 2009 20:54:43

"DanDanDan" < XXXX@XXXXX.COM > writes:




This wording is a little confusing. B is not const so the function is
permitted to set B (it doesn't, but it might). In fact, there isn't a
single const object anywhere in the program. The const is simply a
promise that func won't use B to change the int that B points to.

<snip>
--
Ben.