Compound Statements in C++
Last Updated :
19 Oct, 2023
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++
#include <iostream>
using namespace std;
void GFG()
{
cout << "Hello World" << endl;
}
int main()
{
GFG();
return 0;
}
|
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++
#include <iostream>
using namespace std;
int main()
{
int x = 20;
if (x > 6) {
cout << "x is greater than 6"
<< std::endl;
cout << "Inside the if block"
<< std::endl;
}
return 0;
}
|
Output
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++
#include <iostream>
using namespace std;
int main()
{
int x = 8;
cout << "Outer x: " << x << endl;
{
int x = 30;
cout << "Inner x: " << x << endl;
}
cout << "Outer x: " << x << endl;
return 0;
}
|
Output
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.
Share your thoughts in the comments
Please Login to comment...