Compound Statement
A compound statement is a set of zero or more statements enclosed within curly braces ({}
). It acts as a single statement, allowing the execution of multiple statements as if they were a single unit. Compound statements are often used in control flow structures such as loops and conditional statements, as well as in function bodies.
Syntax of Compound Statements:
The syntax of a compound statement is straightforward:
{
// Statement 1
// Statement 2
// ...
// Statement N
}
The statements within the curly braces can include variable declarations, control flow statements, function calls, and any other valid C++ statements. The compound statement is terminated by the closing curly brace.
Example Usage:
Let's take a look at a simple example illustrating the use of compound statements in a C++ program:
#include <iostream>
int main() {
// Variables with local scope
int x = 5;
int y = 10;
// Compound statement begins
{
int z = x + y; // Local variable within the compound statement
std::cout << "Sum inside compound statement: " << z << std::endl;
} // Compound statement ends
// Variable z is out of scope here and cannot be accessed
// Continue with the rest of the program
return 0;
}