Compound statements in C++ are blocks used to group multiple statements together into a single unit. These statements are enclosed in curly braces {} and can be used wherever a single statement is expected. The statements put inside curly braces are executed just like a single statement would have been executed. The compound statements help in organizing code and provide a way to execute multiple statements sequentially.
Syntax of Compound Statements
The compound statements look like this in the program:
{ // Statements statement1; statement2; // ... statementN; }
We just have to put multiple statements in the braces {}.
Examples of Compound Statements
Example 1: Using Compound Statements with Functions
The compound statements are commonly used within the function definitions. All the statements inside a function’s body are enclosed as the compound statement.
// C++ Program to illustrate Compound Statements in // Functions #include <iostream> using namespace std;
void GFG()
// compound statement start { cout << "Hello World" << endl;
} // compound statement end // driver code int main()
{ GFG();
return 0;
} |
1 2 3 4 5
Example 2: Compound Statement with if Statement
The compound statements are used in if statements for the instance when multiple statements need to be executed conditionally.
// C++ Program to illustrate Compound Statements in // Conditional Statements #include <iostream> using namespace std;
int main()
{ int x = 20;
if (x > 6) {
cout << "x is greater than 6"
<< std::endl; // statement 1
cout << "Inside the if block"
<< std::endl; // statement 2
}
return 0;
} |
x is greater than 6 Inside the if block
Example 3: Simple Compound Statement Inside a Function
In this program, we will use we’ll use a compound statement in between a function which also controls the scope of the variables.
// C++ Program to illustrate Compound Statements in Variable // Scope #include <iostream> using namespace std;
int main()
{ int x = 8; // Outer variable
cout << "Outer x: " << x << endl;
// Variable Scope Starts
{
int x = 30;
cout << "Inner x: " << x << endl;
}
// Variable Scope Ends
// Access the outer x after the inner block scope
cout << "Outer x: " << x << endl;
return 0;
} |
Outer x: 8 Inner x: 30 Outer x: 8
Conclusion
As we have seen, compound statements are an integral part of the C programming languages. It is used with almost all of the components of the C to group the statements together or provide a separate scope.