![]() |
|
|
|||||||
![]() |
C Programming - Same pointer parameter const and non-const |
|
|
Thread Tools | Search this Thread |
|
|
#1 |
|
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)); } Old Wolf |
|
|
|
|
#2 |
|
Posts: n/a
|
On 2009-11-03, Old Wolf <> wrote:
> 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? 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 / usenet- http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! Seebs |
|
|
|
#3 |
|
Posts: n/a
|
"Old Wolf" <> wrote in message news:b5d2ab96-b143-4bb8-8da4-... > 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)); > } 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 **** completely. DanDanDan |
|
|
|
#4 |
|
Posts: n/a
|
"DanDanDan" <> writes:
> "Old Wolf" <> wrote in message > news:b5d2ab96-b143-4bb8-8da4-... >> 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)); >> } > > The const will only mean that func won't set B, it won't assume anything > else. 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. Ben Bacarisse |
|