Const Challenge
C
Hard
3 views
Problem Description
Const int, const pointer, pointer to const - declare all three. Then try modifying them and see which modification is allowed and which one gives a compile error.
Official Solution
#include <stdio.h>
int main() {
/* 1. const int */
const int a = 10;
// a = 20; // ❌ ERROR: cannot modify const int
/* 2. pointer to const int */
int x = 5, y = 15;
const int *p = &x;
// *p = 10; // ❌ ERROR: cannot modify value through pointer
p = &y; // ✅ ALLOWED: pointer can change
/* 3. const pointer to int */
int z = 25;
int *const q = &z;
*q = 30; // ✅ ALLOWED: value can change
// q = &x; // ❌ ERROR: pointer cannot change
printf("a = %dn", a);
printf("Value pointed by p = %dn", *p);
printf("Value pointed by q = %dn", *q);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!