guides:programstyle:codeblocks
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
guides:programstyle:codeblocks [2020/07/24 14:23] – wikiadmin | guides:programstyle:codeblocks [2024/07/25 15:01] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
====== Compound Statements or Code Blocks ====== | ====== Compound Statements or Code Blocks ====== | ||
+ | |||
+ | ===== Short Answer ===== | ||
+ | The body of all control structures should be enclosed in a code block. | ||
+ | |||
+ | Acceptable examples: | ||
+ | <code c++> | ||
+ | |||
+ | if (x > 5) { | ||
+ | big = true; | ||
+ | } | ||
+ | |||
+ | for (i = 0; i < 10; i++) { | ||
+ | cout << i << endl; | ||
+ | } | ||
+ | |||
+ | do { | ||
+ | | ||
+ | } while ( count < 7); | ||
+ | </ | ||
+ | |||
+ | |||
+ | Unacceptable examples: | ||
+ | <code c++> | ||
+ | |||
+ | if (x > 5) | ||
+ | big = true; | ||
+ | |||
+ | for (i = 0; i < 10; i++) | ||
+ | cout << i << endl; | ||
+ | |||
+ | do | ||
+ | | ||
+ | while ( count < 7); | ||
+ | </ | ||
+ | ===== Discussion ===== | ||
In c/c++ statements can be grouped into a single statement using a code block or "curly braces" | In c/c++ statements can be grouped into a single statement using a code block or "curly braces" | ||
Line 11: | Line 46: | ||
< | < | ||
if (boolean expression) { | if (boolean expression) { | ||
- | statement1; | + | statement_1; |
- | statement2; | + | statement_2; |
... | ... | ||
- | statementn; | + | statement_n; |
} | } | ||
</ | </ | ||
+ | |||
+ | When the body of a control structure, such as if, is a single statement, code blocks are not required, however a common convention is to require code a code block for any control statement. | ||
+ | |||
+ | The main reason for this convention is that it allows programmers to modify code without introducing errors. | ||
+ | |||
+ | Consider the following example: | ||
+ | <code c++> | ||
+ | for(i = 0; i < 10; i++) | ||
+ | Process(i); | ||
+ | </ | ||
+ | |||
+ | Assume that //Process// is designed to output a message, however it has a bug in it so it does not produce any output. | ||
+ | <code c++> | ||
+ | for(i = 0; i < 10; i++) | ||
+ | cout << "In the loop, i = " << i << endl; | ||
+ | Process(i); | ||
+ | </ | ||
+ | |||
+ | Unfortunately, | ||
+ | |||
+ | Failure to follow this convention leads to bugs so frequently that as of g++6, there is a flag to warn when this situation occurs (-Wmisleading-indentation). | ||
+ | |||
guides/programstyle/codeblocks.1595600586.txt.gz · Last modified: 2024/07/25 15:01 (external edit)