intadd(intx,inty){// start blockreturnx+y;}// end block (no semicolon)intmain(){// start block// multiple statementsintvalue{};// this is initialization, not a blockadd(3,4);return0;}// end block (no semicolon)
语句块嵌套
尽管函数体内不能嵌入其他函数,但是语句块中是可以嵌入其他语句块的:
1 2 3 4 5 6 7 8 9101112131415161718
intadd(intx,inty){// blockreturnx+y;}// end blockintmain(){// outer block// multiple statementsintvalue{};{// inner/nested blockadd(3,4);}// end inner/nested blockreturn0;}// end outer block
语句块最常用的场景是配合 if 语句来使用。默认情况下,if 语句当条件求值为真时,会执行一条语句。不过,我们可以使用语句块来替换单图语句,这样 if 就能够在求值为真时,执行多条语句。
例如:
1 2 3 4 5 6 7 8 9101112131415161718192021
#include<iostream>intmain(){// start of outer blockstd::cout<<"Enter an integer: ";intvalue{};std::cin>>value;if(value>=0){// start of nested blockstd::cout<<value<<" is a positive integer (or zero)\n";std::cout<<"Double this number is "<<value*2<<'\n';}// end of nested blockelse{// start of another nested blockstd::cout<<value<<" is a negative integer\n";std::cout<<"The positive of this number is "<<-value<<'\n';}// end of another nested blockreturn0;}// end of outer block
如果用户输入的是 3:
123
Enter an integer: 3
3 is a positive integer (or zero)
Double this number is 6
如果用户输入的是 4:
123
Enter an integer: -4
-4 is a negative integer
The positive of this number is 4
语句块嵌套的层数
在语句块中嵌套语句块,再嵌套语句块也是可以的:
1 2 3 4 5 6 7 8 91011121314151617181920
intmain(){// block 1, nesting level 1std::cout<<"Enter an integer: ";intvalue{};std::cin>>value;if(value>0){// block 2, nesting level 2if((value%2)==0){// block 3, nesting level 3std::cout<<value<<" is positive and even\n";}else{// block 4, also nesting level 3std::cout<<value<<" is positive and odd\n";}}return0;}