LearnFrenzy
Sign in Take a free test

Pointers and Dynamic Memory · Find the Error · Question 2

Error: int* pointing to a const int Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

int main() {
    const int limit = 100;
    int* p = &limit;
    *p = 200;
    std::cout << limit << '\n';
    return 0;
}
  • A limit must be global
  • B &limit has type const int*, which cannot convert to int* – that would allow changing a const object Correct
  • C 200 is out of range
  • D *p must be written p*
Correct Answer: Option B

Use const int* p = &limit; for reading. Casting the const away and writing would be undefined behaviour.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links