Compound statement

Compound statement is a set of statements or no statements enclosed within set braces. It is also called as blocks.  Compounds statements are usually used in control flow statements(if, if-else, nested if, for, while, do-while etc).

Example 1: 
if (a < b) {
printf("a is less than b");
printf("I am inside compound statement\n");
}
There are two statements inside the if block which are compound statements.

Example 2: 
for (i = 0; i < 5; i++) {

}

There is no statement present inside the for loop.  It is also called as compound statement.

Example 3: 
for (i = 0; i < 5; i++) {
      int j = 10;  // variable declaration
}
Variable declaration is allowed inside blocks.  But, the scope(lifetime) of the variable is only inside the block where it is declared.

Example c program using compound statements
 
#include <stdio.h>
int main() {
int i = 20;

/* two statements inside if block */
if (i > 10) {
printf("Value of i is greater than 20\n");
printf("Compound statement\n");
}

printf("\nBlock with empty statement!! - start\n");
/* zero statements inside for loop */
for (i = 0; i < 5; i++) {

}
printf("Block with empty statement!! - End\n\n");

/* variable declaration inside for loop */
for (i = 0; i < 5; i++) {
int j = i;
printf("Value of j is %d\n", j);
}
return 0;
}

  Output:
  jp@jp-VirtualBox:~/$ ./a.out 
  Value of i is greater than 20
  Compound statement

  Block with empty statement!! - start
  Block with empty statement!! - End

  Value of j is 0
  Value of j is 1
  Value of j is 2
  Value of j is 3
  Value of j is 4



Compound statement Compound statement Reviewed by Mursal Zheker on Sabtu, Desember 28, 2013 Rating: 5

Tidak ada komentar:

Diberdayakan oleh Blogger.