LearnFrenzy
Sign in Take a free test

Control Instructions · Find the Error · Question 5

Bug: = instead of == in an if condition Answer, explanation & discussion

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

The user has 3 attempts left. What does this program print, and why?

main.c
#include <stdio.h>

int main(void) {
    int attempts = 3;
    if (attempts = 0)
        puts("locked");
    else
        printf("%d attempts left\n", attempts);
    return 0;
}
  • A 3 attempts left
  • B 0 attempts left – attempts = 0 assigns 0 (false), so the else runs with the changed value Correct
  • C locked
  • D It does not compile
Correct Answer: Option B

The condition assigns 0 to attempts and tests 0, which is false. The bug both picks the wrong branch and destroys the value. Use ==, and compile with -Wall to catch it.

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