What happens with const int x = 5; x = 6;?
The compiler rejects any assignment to a const-qualified object ("cannot assign to variable 'x' with const-qualified type"). A const object gets its value only from its initializer.
C Const · Exercise 1 of 4
Twelve multiple-choice questions on const variables, const with pointers, const parameters, const vs #define, casting away const, volatile const and C23 constexpr. Pick an option to check your answer instantly.
What happens with const int x = 5; x = 6;?
The compiler rejects any assignment to a const-qualified object ("cannot assign to variable 'x' with const-qualified type"). A const object gets its value only from its initializer.
Which declaration means the same as const int *p?
The order of const and the type name does not matter; what matters is whether const is before or after the *. Both declare a pointer to a const int.
Is const double pi = acos(-1.0); valid inside a function?
const means "not modified after initialisation", not "known at compile time". Only objects with static storage (globals, static locals) need constant initializers.
At file scope, is const int N = 10; int buf[N]; valid C?
C++ treats a const int initialised with a constant as a constant expression; C does not. Use enum { N = 10 };, #define N 10 or C23 constexpr int N = 10;.
Which statement about #define PI 3.14159 versus const double PI = 3.14159; is true?
The preprocessor substitutes the macro's text before compilation, so it has no type, no address and no scope. The const has a type the compiler checks, obeys block scope and is visible in a debugger.
What is the result of *(int *) &limit = 20; when limit was defined as static const int limit = 10;?
The cast removes the compiler's protection, but the object is still const. Writing to it is undefined: on most systems it sits in read-only memory and the program crashes.
A function is declared void edit(char *s);. What happens when you call edit(msg) with const char *msg?
Adding const is implicit and safe (char * → const char *); removing it is not. The fix is to make edit() take const char * if it does not write, or pass a modifiable copy.
What type does the string literal "hi" have in C?
For historical reasons, string literals are char arrays in C (they are const char arrays in C++). So char *s = "hi"; compiles without a warning, but writing through s is undefined. Declare const char *s.
What is the effect of const in int square(const int n)?
Arguments are copied, so the caller is never affected either way. The const just stops the function body from reassigning its parameter – and it is not part of the function's type for callers.
For const int *const p = &x;, which is allowed?
The first const protects the int, the second the pointer. Only reading through p is allowed.
Timed online tests with instant scores and explanations.