LearnFrenzy
Sign in Take a free test

Basic Syntax and Data Types · Find the Error · Question 10

Error: using a variable outside its block Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

int main() {
    int n = 4;
    if (n > 0) {
        int square = n * n;
    }
    std::cout << square << '\n';
    return 0;
}
  • A n must be const
  • B square is declared inside the if block, so it does not exist after the closing brace Correct
  • C if needs an else
  • D n * n overflows
Correct Answer: Option B

A variable lives from its declaration to the end of the enclosing block. Declare int square = 0; before the if and assign inside 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