LearnFrenzy
Sign in Take a free test

C Const · Find the Error · Question 3

Error: changing a member of a const struct Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

struct point {
    int x, y;
};

int main(void) {
    const struct point origin = {0, 0};
    origin.x = 5;
    printf("%d\n", origin.x);
    return 0;
}
  • A Structs cannot be const
  • B origin is const, so every member is read-only; copy it into a non-const struct to change it Correct
  • C x must be declared const inside the struct
  • D There is no bug
Correct Answer: Option B

const applies to the whole object, including all its members. Make a modifiable copy: struct point p = origin; p.x = 5;.

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