Const Pointer in C

Level 5254 keystrokes

Compares three const placements: a pointer to const can be redirected but cannot change the value, a const pointer can change the value but not be redirected, and a const pointer to const allows neither. It prints 10, 20, then 30 twice after writing through ptr2.

C code

// Two ints the pointers will point to
1int a = 10, b = 20;
2
// Pointer to const: *ptr1 = ... is an error, but ptr1 may point elsewhere
3const int *ptr1 = &a;
// Const pointer: *ptr2 may be changed, but ptr2 always points to a
4int *const ptr2 = &a;
// Const pointer to const: neither the value nor the pointer can change
5const int *const ptr3 = &a;
6
// Reading through a pointer to const is fine: prints *ptr1: 10
7printf("*ptr1: %d\n", *ptr1);
// Redirects ptr1 to b, which is allowed
8ptr1 = &b;
// ptr1 now points to b: prints *ptr1 after: 20
9printf("*ptr1 after: %d\n", *ptr1);
10
// Writes 30 into a through the const pointer
11*ptr2 = 30;
// a itself changed: prints *ptr2: 30, a: 30
12printf("*ptr2: %d, a: %d\n", *ptr2, a);
13
// ptr3 can only read; it sees the new value of a: prints *ptr3: 30
14printf("*ptr3: %d\n", *ptr3);

Output

*ptr1: 10
*ptr1 after: 20
*ptr2: 30, a: 30
*ptr3: 30
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • *× 12
  • ;× 10
  • "× 8
  • ,× 7
  • =× 7
  • :× 5
  • %× 5
  • (× 4
  • )× 4
  • \× 4

More C examples at level 5

← C typing practice