Can a pointer to const and a regular pointer be mixed?

Is * b undefined when calling printf ()?

void foo(int *a) {
  const int *b = a;
  int *c = a;
  *c = 2;
  printf("%d\n", *b); // what must be *b? 1, 2 or undefined?
}

int d = 1;
foo(&d);
+5
source share
6 answers

It will print 2. const int *bliterally means:

Pointer to an integer whose value cannot be changed by delimiting it.

This does not mean that the value pointed to by the pointer may not change. In fact, this is absolutely true for the change. A likely scenario for using this is structures that contain a read-only link for some large structure. The link may change, but functions that work with this structure cannot change what is behind the pointer.

, , : , , . OTOH, , , .

+11

( )

6.7.3/5

,    const- lvalue -    const-qualified type, undefined.

( ).
, , (int) .

b ; a c

+2

b , a, , , . , c, . 2.

0

*b 2, printf, , *c = 2.

a, b c . , , .

0

b 2 printf(). b c.

0

const int *b = a; , b int. , .

,

*b = 10;

, :

a = 10;

, a , b .

, b , , :

c = 2;

. , const , , , .

0

All Articles