Same pointer parameter const and non-const

O

Old Wolf

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));
}
 
S

Seebs

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
 
D

DanDanDan

Old Wolf said:
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
shit completely.
 
B

Ben Bacarisse

DanDanDan said:
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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top