π Lecture 29 β File handling tips for Java and C++
π Overview: This lecture covers important file handling conventions and coding standards for Java and C++. It establishes guidelines for file organization, include statements, class declarations, and statement formatting, which are crucial for maintaining readable, consistent, and error-free code in multi-programmer environments.
ποΈ Topics Covered
File handling tips for Java and C++ including header file extensions, class declaration conventions, and include file constructions. Organization of class and interface declarations with proper ordering of variables, constructors, and methods. Comprehensive guidelines for statements including type conversions, variable declarations, loop structures, conditionals, and miscellaneous coding practices like avoiding magic numbers and using explicit type conversions.
π Lecture Summary
File handling tips for Java and C++
C++ header files should have the extension .h. Source files can have the extension .c++ (recommended), .C, .cc or .cpp. Example: MyClass.c++, MyClass.h. These are all accepted C++ standards for file extension.
Classes should be declared in individual header files with the file name matching the class name. Secondary private classes can be declared as inner classes and reside in the file of the class they belong to. All definitions should reside in source files. The header files should declare an interface, the source file should implement it. When looking for an implementation, the programmer should always know that it is found in the source file. The obvious exception to this rule is inline functions that must be defined in the header file.
Special characters like TAB and page break must be avoided. These characters are bound to cause problems for editors, printers, terminal emulators or debuggers when used in a multi-programmer, multi-platform environment.
π Definition β Inline functions: Functions that must be defined in the header file, as they are the exception to the rule that definitions should reside in source files.
Include Files and Include Statements for Java and C++
Header files must include a construction that prevents multiple inclusion. The convention is an all uppercase construction of the module name, the file name and the h suffix.
#ifndef MOD_FILENAME_H
#define MOD_FILENAME_H
:
#endif
The construction is to avoid compilation errors. The construction should appear in the top of the file (before the file header) so file parsing is aborted immediately and compilation time is reduced.
Classes and Interfaces
Class and Interface declarations should be organized in the following manner:
- Class/Interface documentation.
classorinterfacestatement.- Class (static) variables in the order public, protected, package (no access modifier), private.
- Instance variables in the order public, protected, package (no access modifier), private.
- Constructors.
- Methods (no specific order).
Statements in Java and C++
Types
Type conversions must always be done explicitly. Never rely on implicit type conversion.
floatValue = (float) intValue; // NOT: floatValue = intValue;
By this, the programmer indicates that he is aware of the different types involved and that the mix is intentional.
Types that are local to one file only can be declared inside that file.
The parts of a class must be sorted public, protected and private. All sections must be identified explicitly. Not applicable sections should be left out. The ordering is "most public first" so people who only wish to use the class can stop reading when they reach the protected/private sections.
π‘ Why this matters: This ordering puts the most relevant information first for users of the class, while implementers can read further to understand the protected and private details.
Variables
Variables should be initialized where they are declared and they should be declared in the smallest scope possible.
Variables must never have dual meaning. This enhances readability by ensuring all concepts are represented uniquely. This reduces chance of error by side effects.
Class variables should never be declared public. The concept of information hiding and encapsulation is violated by public variables. Use private variables and access functions instead. One exception to this rule is when the class is essentially a data structure, with no behavior (equivalent to a C++ struct). In this case it is appropriate to make the class' instance variables public.
Related variables of the same type can be declared in a common statement. Unrelated variables should not be declared in the same statement.
float x, y, z;
float revenueJanuary, revenueFebrury, revenueMarch;
The common requirement of having declarations on separate lines is not useful in the situations like the ones above. It enhances readability to group variables.
Variables should be kept alive for as short a time as possible. Keeping the operations on a variable within a small scope makes it easier to control the effects and side effects of the variable.
Global variables should not be used. Variables should be declared only within scope of their use. Same is recommended for global functions or file scope variables. It is easier to control the effects and side effects of the variables if used in limited scope.
Implicit test for 0 should not be used other than for boolean variables and pointers.
if (nLines != 0) // NOT: if (nLines)
if (value != 0.0) // NOT: if (value)
It is not necessarily defined by the compiler that ints and floats 0 are implemented as binary 0. Also, by using explicit test the statement gives immediate clue of the type being tested. It is common also to suggest that pointers shouldn't test implicit for 0 either, i.e. if (line == 0) instead of if (line). The latter is regarded as such a common practice in C/C++ however that it can be used.
Loop structures
Only loop control statements must be included in the for() construction.
sum = 0; // NOT: for (i=0, sum=0; i<100; i++)
for (i=0; i<100; i++) // sum += value[i];
sum += value[i];
Loop variables should be initialized immediately before the loop.
boolean done = false; // NOT: boolean done = false;
while (!done) { // :
: // while (!done) {
} // :
The use of do .... while loops should be avoided. There are two reasons for this. First, the construct is superfluous; any statement that can be written as a do .... while loop can equally well be written as a while loop or a for loop. Complexity is reduced by minimizing the number of constructs being used. The other reason is readability. A loop with the conditional part at the end is more difficult to read than one with the conditional at the top.
The use of break and continue in loops should be avoided. These statements should only be used if they prove to give higher readability than their structured counterparts. In general, break should only be used in case statements and continue should be avoided altogether.
The form for (;;) should be used for empty loops.
for (;;) { // NOT: while (true) {
: // :
} // }
This form is better than the functionally equivalent while (true) since this implies a test against true, which is neither necessary nor meaningful. The form while(true) should be used for infinite loops.
Conditionals
Complex conditional expressions must be avoided. Introduce temporary boolean variables instead.
if ((elementNo < 0) || (elementNo > maxElement)||
elementNo == lastElement) {
:
}
Should be replaced by:
boolean isFinished = (elementNo < 0) || (elementNo > maxElement);
boolean isRepeatedEntry = elementNo == lastElement;
if (isFinished || isRepeatedEntry) {
:
}
The nominal case should be put in the if-part and the exception in the else-part of an if statement.
boolean isError = readFile (fileName);
if (!isError) {
:
}
else {
:
}
The conditional should be put on a separate line.
if (isDone) // NOT: if (isDone) doCleanup();
doCleanup();
Executable statements in conditionals must be avoided.
file = openFile (fileName, "w"); // NOT: if ((file = openFile(fileName, "w")) != null) {
if (file != null) { // :
: // }
}
Miscellaneous
The use of magic numbers in the code should be avoided. Numbers other than 0 and 1 should be considered declared as named constants instead.
Floating point constants should always be written with decimal point and at least one decimal.
double total = 0.0; // NOT: double total = 0;
double speed = 3.0e8; // NOT: double speed = 3e8;
double sum;
:
sum = (a + b) * 10.0;
This emphasizes the different nature of integer and floating point numbers even if their values might happen to be the same in a specific case. Also, as in the last example above, it emphasizes the type of the assigned variable (sum) at a point in the code where this might not be evident.
Floating point constants should always be written with a digit before the decimal point.
double total = 0.5; // NOT: double total = .5;
The number and expression system in Java is borrowed from mathematics and one should adhere to mathematical conventions for syntax wherever possible. Also, 0.5 is a lot more readable than .5; there is no way it can be mixed with the integer 5.
Functions in C++ must always have the return value explicitly listed.
int getValue() // NOT: getValue()
{
:
}
If not explicitly listed, C++ implies int return value for functions.
goto in C++ should not be used. Goto statements violate the idea of structured code. Only in some very few cases (for instance breaking out of deeply nested structures) should goto be considered, and only if the alternative structured counterpart is proven to be less readable.
β Key Takeaways
The lecture emphasizes consistent file organization and coding standards across Java and C++. Critical rules include: header files must have multiple inclusion guards using #ifndef constructs; classes should be declared in individual header files with matching names; type conversions must be explicit to avoid ambiguity; variables should be declared in the smallest possible scope and initialized immediately; complex conditionals should be replaced with temporary boolean variables for readability; magic numbers must be avoided in favor of named constants; loop constructs like do...while, break, continue should be minimized; and global variables should never be used to maintain encapsulation. These practices ensure code is maintainable, readable, and minimizes errors in multi-programmer environments.
π§ Quick Revision Questions
- What is the purpose of the
#ifndef/#define/#endifconstruction in C++ header files, and where should it be placed in the file? - In what order should class/interface variables and constructors be declared, and why is "most public first" the recommended ordering?
- Why should complex conditional expressions be avoided, and what is the recommended alternative using a code example?
- What is the rule about implicit testing for 0, and which types are exceptions to this rule?
- Why should
do...whileloops andgotostatements be avoided in C++ code?
π Lecture No. 30 β Layout and Comments in Java and C++
π Overview: This lecture addresses code readability and maintainability by establishing guidelines for comments, expressions, statements, and avoiding cryptic code. It emphasizes making code self-documenting through proper formatting and clear logic rather than relying on comments or clever shortcuts.
ποΈ Topics Covered
The lecture covers commenting guidelines for Java and C++, including the problem with comments and proper indentation. It then addresses expression and statement layout, including natural form for expressions, parenthesization, and breaking down complex expressions. Finally, it warns against shortcuts and cryptic code, providing examples of common pitfalls and better alternatives.
π Lecture Summary
10.6 Layout and Comments in Java and C++
Comments present a fundamental problem: they lie. Comments are not syntax checked, and there is nothing forcing them to be accurate. As code undergoes change during schedule crunches, comments become less and less accurate.
As Fowler puts it, comments should not be used as deodorants. Tricky code should not be commented but rewritten. In general, the use of comments should be minimized by making the code self-documenting through appropriate name choices and an explicit logical structure.
If comments are necessary, these guidelines should be observed:
- All comments should be written in English (preferred in international environments)
- Use // for all comments, including multi-line comments. Since multilevel commenting is not supported in C++ and Java, using // ensures it is always possible to comment out entire sections using /* */ for debugging.
- Comments should be indented relative to their position in the code
π Definition β Self-documenting code: Code that is written clearly enough through appropriate naming and logical structure that it does not need comments to be understood.
π Example of proper comment indentation:
// CORRECT:
while (true) {
// Do something
something();
}
// NOT:
while (true) {
// Do something
//
// Do something
something();
}
10.7 Expressions and Statements Layout
Basic indentation should be 2 spaces. Indentation of 1 is too small to emphasize the logical layout. Indentation larger than 4 makes deeply nested code difficult to read and increases the chance that lines must be split. 2 is chosen to reduce the chance of splitting code lines.
π Formula: Indentation = 2 spaces β optimal balance between readability and avoiding line splitting
Natural form for expressions: Expressions should be written as if they were spoken out aloud. Conditional expressions with negation are always difficult to understand.
π Example of rewriting with natural form:
// PROBLEMATIC:
if (! (block < activeBlock) || !(blockId >= unblocks))
// BETTER:
if ((block >= activeBlock) || (blockId < unblocks))
Parenthesize to remove ambiguity: Parentheses should always be used as they reduce complexity and clarify grouping. This is especially important when different unrelated operators are used in the same expression, as precedence rules are often assumed incorrectly by programmers.
π Example of precedence error:
// PROBLEMATIC: == has higher precedence than &
if (x & MASK == BITS)
// This compares MASK and BITS first, then ANDs result with x
// CORRECT with parentheses:
if ((x & MASK) == BITS)
π Example with leap year calculation:
// AMBIGUOUS:
leapYear = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ;
// SELF-EXPLANATORY:
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
Break up complex expressions: An expression is considered complex if it uses many operators in a single statement. Complex expressions should be broken down into multiple statements.
π Example of breaking down:
// PROBLEMATIC - too complex:
*x += (*xp=(2*k < (n-m) ? c[k+1] : d[k--]));
// BETTER - broken down:
if (2*k < n-m)
*xp = c[k+1];
else
*xp = d[k--];
*x = *x + *xp;
10.8 Shortcuts and Cryptic Code
Programmers sometimes write very concise code using shortcuts and tricks, resulting in cryptic code that is difficult to follow. Maintenance of such code becomes a nightmare.
Example 1 - Operator shortcuts:
// PROBLEMATIC - ambiguous semantics:
x *= a + b; // Is this x = x*a+b or x = x*(a+b)?
// The second is correct but not obvious from syntax
Example 2 - Complex shift operations:
// PROBLEMATIC - cryptic:
subkey = subkey >> (bitoff β (bitoff >> 3) << 3));
// This masks bitoff with octal 7
// BETTER:
subkey = subkey >> (bitoff & 0x7);
Example 3 - Hidden semantics with shifts:
// PROBLEMATIC - intent hidden:
a = a >> 2;
// Technical means divide by 4, but intent is unclear
// BETTER - explicit intent:
a = a/4;
Example 4 - Circular queue implementation:
// PROBLEMATIC - using % operator obscures logic:
bool Queue::add(int n) {
int k = (rear+1) % MAX_SIZE;
if (front == k) return false;
else {
rear = k;
queue[rear] = n;
return true;
}
}
// BETTER - explicit logic:
bool Queue::add() {
if (! isFull() ) {
rear++;
if (rear == MAX_SIZE) rear = 0;
QueueArray[rear] = n;
size++;
return true;
}
else return false;
}
bool Queue::isFull(int n) {
if (size == MAX_SIZE) return true;
else return false;
}
π‘ Why this matters: The explicit logic version made it easy for students to implement double-ended queues correctly, while the cryptic version using % caused almost everyone to make mistakes with operations like rear = (rear-1) % MAX_SIZE.
β Key Takeaways
Comments lie and should be minimized; instead, make code self-documenting through proper naming and logical structure. Always use // for comments (not /* */), indent them properly, and write in English. Use 2-space indentation for blocks, write expressions in natural spoken form, always parenthesize to clarify operator precedence, and break complex expressions into multiple statements. Avoid cryptic shortcuts like using bit shifts for division (use a/4 instead of a>>2) or tricky modulo operations for circular structures; state logic explicitly and use counting (size) instead of tricky pointer comparisons.
π§ Quick Revision Questions
-
Why does Fowler say "comments should not be used as deodorants"? What should be done instead of commenting tricky code?
-
What is the recommended indentation size and why was this specific size chosen?
-
In the leap year example, why does adding parentheses make the code self-documenting when the logic hasn't actually changed?
-
Convert the following cryptic statement into clearer code and explain why:
a = a >> 2; -
What specific problem arose when students attempted to implement a double-ended queue using the
%operator approach, and how did the explicit counting approach solve it?
π Lecture 31 β Coding Style Guidelines (Continued)
π Overview: This lecture continues the discussion of coding style guidelines, focusing on problematic programming practices that reduce code readability and maintainability. It covers proper switch statement construction, the dangers of magic numbers, and appropriate use of the number zero in C/C++ programs, emphasizing the importance of self-documenting code.
ποΈ Topics Covered
The lecture examines three specific coding style issues: proper switch statement formatting with explicit break statements to avoid confusing fall-through behavior, the problem of magic numbers (unnamed constants) and how to replace them with named enumerated constants, and the misuse of the number zero for multiple different purposes in C/C++ code. Each topic includes concrete examples showing both poor and improved coding practices.
π Lecture Summary
Switch Statement
Switch statements should always end each case with a break statement. A tricky sequence of fall-through code like the one below causes more trouble than being helpful.
switch(c) {
case '-': sign = -1;
case '+': c = getchar();
case '.': break;
default: if (! isdigit(c))
return 0;
}
This code is cryptic and difficult to read. It is much better to explicitly write what is happening, even at the cost of duplication.
switch(c) {
case '-': sign = -1;
c = getchar();
break;
case '+': c = getchar();
break;
case '.': break;
default: if (! isdigit(c))
return 0;
break;
}
It would even be better if such code is written using the if statement as shown below.
if (c == '-') {
sign = -1;
c = getchar();
}
else if (c == '+') {
c = getchar();
}
else if (c != '.' && !isdigit(c)) {
return 0;
}
π Definition β Fall-through: The behavior in a switch statement where execution continues from one case to the next without a break statement, which is often confusing and should be avoided in most situations.
Magic Numbers
Consider the following code segment:
fac = lim / 20;
if (fac < 1)
fac = 1;
for (i =0, col = 0; i < 27; i++, j++) {
col += 3;
k = 21 β (let[i] /fac);
star = (let[i] == 0) ? ' ' : '*';
for (j = k; j < 22; j++)
draw(j, col, star);
}
draw(23, 1, ' ');
for (i='A'; i <= 'Z'; i++)
cout << i;
Can you tell by reading the code what is meant by the numbers 20, 27, 3, 21, 22, and 23? These are constants that mean something but they do not give any indication of their importance or derivation, making the program hard to understand and modify. To a reader they work like magic and hence are called magic numbers. Any number (even 0 or 1) used in the code is a magic number. It should rather have a name of its own that can be used in the program instead of the number.
The difference would be evident if we look at the code segment below that achieves the same purpose:
enum {
MINROW = 1,
MINCOL = 1,
MAXROW = 24,
MAXCOL = 80,
LABELROW = 1,
NLET = 26,
HEIGHT = MAXROW β4,
WIDTH = (MAXCOL-1) / NLET
};
fac = (lim+HEIGHT-1) /HEIGHT;
if (fac < 1)
fac = 1;
for (i =0; i < NLET; i++) {
if (let[i] == 0)
continue;
for (j = HEIGHT β let[i] / fac; j < HEIGHT; j++)
draw(j-1 + LABELROW, (i+1)*WIDTH, '*');
}
draw(MAXROW-1, MINCOL+1, ' ');
for (i='A'; i <= 'Z'; i++)
cout << i;
π Definition β Magic numbers: Any numeric constant (including 0 or 1) appearing directly in code without a named symbolic constant to explain its meaning, making the code difficult to understand and modify.
π Example: In the first code, 27 represents the number of letters in the alphabet (which should be NLET = 26), 20 represents a height calculation (HEIGHT = MAXROW β 4 = 20), and 23 represents the maximum row (MAXROW β 1 = 23). The improved version replaces all these with meaningful names.
π‘ Why this matters: Magic numbers create maintenance nightmares β if a value changes, you must find and update every occurrence manually, and there's no indication of which numbers are related.
Use (or abuse) of Zero
The number 0 is the most abused symbol in programs written in C or C++. One can easily find code segments that use 0 in a fashion similar to the examples below in almost every C/C++ program.
flag = 0; // flag is boolean
str = 0; // str is string
name[i] = 0; // name is char array
x = 0; // x is floating pt
i = 0; // i is integer
This is a legacy of old style C programming. It is much better to use symbols to explicitly indicate the intent of the statement. It is easy to see that the following code is more in line with the self-documentation philosophy than the code above.
flag = false;
str = NULL;
name[i] = '\0';
x = 0.0;
i = 0;
π Definition β Self-documenting code: Code that uses meaningful symbolic constants and type-appropriate values instead of generic numbers, making the programmer's intent clear without requiring comments.
π Example: str = 0 is ambiguous β does it mean the string is empty, or the pointer is null? Using str = NULL explicitly indicates a null pointer, while str = "" would indicate an empty string.
π‘ Why this matters: Using 0 for multiple purposes (boolean false, null pointer, null character, floating point zero, integer zero) confuses readers and can hide bugs, especially in languages with weak type checking.
β Key Takeaways
Switch statements must always include explicit break statements at the end of each case to prevent confusing fall-through behavior; consider using if-else statements when the switch logic becomes complex. Magic numbers β any unnamed constant in code β must be replaced with named symbolic constants or enumerations to make code understandable and maintainable. The number zero should never be used as a generic placeholder for different data types; instead, use false for booleans, NULL for pointers, '\0' for null characters, and 0.0 for floating-point values. Self-documenting code is achieved by choosing the right symbolic constant for each context, which eliminates the need for explanatory comments about what values mean. These three practices directly improve code clarity, reduce bugs during maintenance, and make programs easier for other developers to understand.
π§ Quick Revision Questions
- Why is fall-through behavior in switch statements considered problematic, and what is the recommended alternative?
- What is a magic number, and how do you fix code that contains magic numbers?
- In the magic numbers example, what did the number
27represent, and why was this incorrect? - What are four different symbolic constants that should replace the number
0in boolean, pointer, character, and floating-point contexts? - What is the principle of self-documenting code, and how does it apply to the three topics covered in this lecture?
π Lecture 32 β Clarity through Modularity
π Overview: This lecture explores how breaking code into smaller, modular functions improves readability and maintainability. It also covers important C/C++ programming pitfalls including short-circuiting of logical operators and operand evaluation order with side effectsβcritical concepts for writing reliable, bug-free software.
ποΈ Topics Covered
The lecture covers three main topics: using modularity to achieve clarity in code through function decomposition, demonstrated with selection sort and quick sort examples; short-circuiting behavior of logical operators && and || with practical examples of guard conditions; and operand evaluation order combined with side effects, showing how unspecified function evaluation order leads to unpredictable results when functions modify parameters or global state.
π Lecture Summary
Clarity through modularity
Abstraction and encapsulation help manage program complexity. Breaking large functions into smaller ones improves readability. The selection sort example shows how a single function can be decomposed into swap and minimum functions, making the code shorter and more readable. As a byproduct, these smaller functions become reusable. Reusability is important but modularity is equally criticalβfunctions should be broken into smaller pieces even if those pieces are not reused elsewhere.
π Definition β Modularity: The practice of breaking a program into smaller, self-contained functions or modules to improve readability, maintainability, and reusability.
π Example: Original selectionSort function (single function with nested loops) was decomposed into:
void swap(int &x, int &y)β swaps two valuesint minimum(int a[], int from, int to)β finds minimum element index in a rangevoid selectionSort(int a[], int size)β now clear, calls minimum() and swap()
The quickSort algorithm demonstrates the same principle. The original code (approximately 25 lines) is difficult to remember. After decomposition into partition and recursive calls, the algorithm becomes trivial:
void quickSort(int a[], int left, int right) {
int p;
if (left < right) {
p = partition(a, left, right);
quickSort(a, left, p-1);
quickSort(a, p+1, right);
}
}
π‘ Why this matters: Modular decomposition transforms complex algorithms into understandable, maintainable code that can be independently tested and reused.
Short circuiting || and &&
The logical operators && (AND) and || (OR) in C/C++ follow the short circuiting rule: expressions are evaluated left to right, and evaluation stops as soon as the final truth value can be determined. Short-circuiting allows one boolean expression to "guard" a potentially unsafe operation in a second expression, and saves time in complex expression evaluation.
π Definition β Short circuiting: A property of logical operators where evaluation stops as soon as the overall result is known, without evaluating remaining operands.
π Example: A commercial banking software had this incorrect code:
while (ptr->data < myData && ptr != NULL) { // WRONG order
The guard ptr != NULL was placed second, but due to short-circuiting, the first expression ptr->data is evaluated first. If ptr is NULL, accessing ptr->data causes a crash. The corrected version:
while (ptr != NULL && ptr->data < myData) { // CORRECT order
Now if ptr is NULL, the first condition fails and the second is never evaluated.
π‘ Why this matters: Always place guard conditions (like null checks) first before the potentially unsafe operations they protect.
Operand Evaluation Order and Side Effects
A side effect occurs when a function, besides returning a value, changes either one of its parameters or a variable declared outside the function. Side effects are a major source of programming errors. Many languages (including C/C++) do not specify function evaluation order in a single statement, which combined with side effects causes major problems.
π Definition β Side effect: Any change to a parameter or external variable made by a function in addition to returning its explicit result.
π Example 1: With different parameters
c = f1(a) + f2(b);
// Functions:
int f1(int &x) { x = x * 2; return x + 1; }
int f2(int &y) { y = y / 2; return y - 1; }
// Initial: a=3, b=4
// Result: a=6, b=2, c=8
This works fine because different variables are affected.
π Example 2: With the same variable (problematic)
c = f1(a) + f2(a);
// Initial: a=3
If f1 evaluated first: a becomes 6, f1 returns 7, then f2 uses a=6, changes to 3, returns 2 β c=9, a=6 If f2 evaluated first: a becomes 1, f2 returns 0, then f1 uses a=1, changes to 2, returns 3 β c=3, a=2 Different order β completely different results!
π‘ Why this matters: Never write code that depends on evaluation order when functions have side effects, as different compilers or platforms may evaluate in different orders.
β Key Takeaways
Modularity dramatically improves code readability and should be applied even when functions are not reusedβthe selection sort and quick sort examples demonstrate this principle. When using short-circuiting operators && and ||, always place guard conditions (like null checks) first to prevent unsafe operations from being executed. Side effects in functions create dangerous dependencies on evaluation order, which is unspecified in C/C++βavoid relying on evaluation order when functions modify parameters or global state. Functions with side effects should be redesigned to separate computation from state modification. Always prefer pure functions (no side effects) for clarity and reliability.
π§ Quick Revision Questions
- What are the two benefits of breaking the selectionSort function into smaller functions (swap and minimum)?
- In the quickSort example, what does the partition function do and why does this improve readability?
- What is wrong with
while (ptr->data < myData && ptr != NULL)and how should it be corrected? - Why does
c = f1(a) + f2(a)produce different results depending on evaluation order? - What is a side effect and why is it dangerous in C/C++ when combined with unspecified evaluation order?
π Lecture 33 β Common Coding Mistakes
π Overview: This lecture addresses two critical aspects of software engineering: common coding mistakes caused by side effects and performance optimization strategies. Understanding side effects helps programmers avoid subtle, hard-to-debug errors, while performance profiling teaches how to efficiently optimize code by focusing on bottlenecks rather than premature optimization.
ποΈ Topics Covered
The lecture covers common coding mistakes resulting from side effects in expressions involving array indices and assignments, along with guidelines to avoid these hazards. It then transitions to performance considerations, explaining the 80/20 rule, profiling techniques, and strategies for optimizing bottlenecks by either using better algorithms or rewriting problematic code sections, with detailed examples from an isspam function case study.
π Lecture Summary
Common Coding mistakes
Following is a short list of common mistakes made due to side effects β where an expression modifies a variable and also uses that same variable, causing unpredictable results.
-
array[i++] = i;β If i is initially 3, the array element might be set to 3 or 4, depending on the order of evaluation. -
array[i++] = array[i++] = x;β Due to side effects, multiple assignments become very dangerous. The result depends entirely on when i is incremented. -
The comma operator (
,) is very dangerous as it causes side effects. Consider:int i, j = 0;β Many people assume i is also initialized to 0, but it is not. Similarly,a = b, c = 0;β A majority of programmers would assume all a, b, and c are being initialized to 0, while only c is initialized and a and b have garbage values. This kind of overlook causes major programming errors that are not caught easily.
π‘ Why this matters: Side effects in expressions create dependencies on evaluation order, which varies across compilers and can produce different results each time the code is executed.
π Definition β Side Effect: A side effect occurs when an expression modifies the value of a variable while also using that variable elsewhere in the same expression, leading to unpredictable behavior based on evaluation order.
π Guidelines to avoid side effects:
- Never use
,except for declarations - If you are initializing a variable at declaration time, do not declare another variable in the same statement
- Never use multiple assignments in the same statement
- Be very careful when you use functions with side effects β functions that change the values of the parameters
- Try to avoid functions that change the value of some parameters and return some value at the same time
Performance
In many cases, performance and maintainability are at odds with one another. When planning for performance, one should always remember the 80/20 rule β you spend 80 percent of your time in 20 percent of the code. That is, we should not try to optimize everything. The proper approach is to profile the program and then identify bottlenecks to be optimized. This is similar to database normalization β we normalize to remove redundancies but then partially de-normalize if there are performance issues.
π Definition β Profiling: The process of measuring where a program spends its execution time to identify performance bottlenecks (the "hot spots").
As an example, consider the isspam function profiled by calling it 10000 times. The results showed:
- strchr: 113 seconds, 44% of time, 900009440 calls
- strncmp: 15 seconds, 28% of time, 156646000 calls
- strstr: 6 seconds, 8% of time, 854500000 calls
- strlen: 4 seconds, 56% of time, 22555934 calls
- isspam: 21 seconds, 95% of time, 28510000 calls
- 11 other functions had insignificant performance overhead
The profiling revealed that most time was spent in strchr and strncmp, and both were called from strstr.
When a small set of functions that use each other is overwhelmingly the bottleneck, there are two alternatives:
- Use a better algorithm
- Rewrite the whole set
In this case, strstr was rewritten and profiled again. Although it was much faster, now 99.8% of the time was spent in strstr. The algorithm was rewritten again by eliminating strstr, strchr, and strncmp and using memcmp. While memcmp was much more complex than strstr, it gained efficiency by eliminating a number of loops. The new results showed:
- memcmp: 880 seconds, 88% of time, 1027590000 calls
- isspam: 66 seconds, 55% of time, 902920000 calls
- strlen: only 140 seconds, 3041060 calls (down from over 2 million)
The trick is to concentrate on hot spots by first identifying them and then cooling them. As mentioned, most time is spent in loops, so loops need to be the focus.
Consider this example:
for (j = i; j < MAX_FIELD; j++)
clear(j);
This loop clears fields before each new input is read. It was taking almost 50% of total time. On investigation, MAX_FIELD was 200 but actual fields needing clearing were 2 or 3 in most cases. The code was modified to:
for (j = i; j < maxField; j++)
clear(j);
This reduced overall execution time by half.
π Example: The MAX_FIELD loop optimization β by replacing the constant 200 with a variable that tracked actual fields needing clearing (typically 2-3), execution time was halved from ~50% of total runtime to ~25%.
β Key Takeaways
The two most critical lessons from this lecture are: first, side effects in expressions like array[i++] = i or multiple assignments create unpredictable behavior that depends on compiler evaluation order β the guidelines provide a simple way to avoid these errors entirely. Second, performance optimization should follow the 80/20 rule: never optimize prematurely, instead profile to find the 20% of code consuming 80% of time, focus on hot spots (especially loops), and be willing to rewrite entire function sets or replace algorithms entirely rather than making small tweaks. The isspam case study demonstrates how replacing three string functions with one (memcmp) eliminated multiple loops and dramatically improved performance.
π§ Quick Revision Questions
- What makes the statement
array[i++] = idangerous, and why might different compilers give different results? - What are the five guidelines given to avoid side-effect-related coding errors?
- What is the 80/20 rule in the context of performance optimization, and why should we not optimize everything?
- In the isspam profiling example, what was the final optimization strategy and why did it work better than just rewriting strstr?
- How did changing
MAX_FIELDtomaxFieldin the loop example reduce execution time by half?
π Lecture 34 β Portability
π Overview: This lecture addresses the critical challenge of making software portable across different platforms. It explains why portability matters for cost-effective software deployment and provides practical guidelines for writing code that can be moved between environments with minimal rework. The lecture covers common portability pitfalls and how to avoid them.
ποΈ Topics Covered
The lecture explores portability through multiple dimensions: sticking to standards and programming in the mainstream, data type size variations across platforms, order of evaluation differences, signedness of char, arithmetic vs logical shift operators, byte order and data exchange issues, alignment within structures, and the problems with bit fields. Each topic is illustrated with code examples showing how platform-dependent behavior can cause failures.
π Lecture Summary
10.13 Portability
Many applications need to be ported onto many different platforms. As we have seen, it is pretty hard to write error free, efficient, and maintainable software. So, if a major rework is required to port a program written for one environment to another, it will probably not come at a low cost. We ought to find ways and means by which we can port applications to other platforms with minimum effort. The key lies in how we write our program. If we are careful during writing code, we can make it portable. On the other hand if we write code without portability in mind, we may end up with code that is extremely hard to port to other environments.
Stick to the standard
- Use ANSI/ISO standard C++
- Instead of using vendor specific language extensions, use STL as much as possible
Program in the mainstream
Although C++ standard does not require function prototypes, one should always write them.
double sqrt(); // old style acceptable by ANSI C
double sqrt(double); // ANSI β the right approach
Size of data types
Sizes of data types cause major portability issues as they vary from one machine to the other.
int i, j, k;
...
j = 20000;
k = 30000;
i = j + k;
// works if int is 4 bytes
// what will happen if int is 2 bytes?
Order of Evaluation
As mentioned earlier during the discussion of side effects, order of evaluation varies from one implementation to another. This therefore also causes portability issues.
Signedness of char
The language does not specify whether char is signed or unsigned.
char c;
// between 0 and 255 if unsigned
// -128 to 127 if signed
c = getchar();
if (c == EOF) ??
// will fail if it is unsigned
It should therefore be written as follows:
int c;
c = getchar();
if (c == EOF)
π Definition β EOF: End-of-file indicator, a special value (typically -1) returned by functions like getchar() to indicate that no more data is available.
π Example: Using char c = getchar() and checking if (c == EOF) will fail if char is unsigned (0-255 range) because EOF is typically -1, which cannot be represented in unsigned char.
Arithmetic or Logical Shift
The C/C++ language has not specified whether right shift >> is arithmetic or logical. In arithmetic shift the sign bit is copied while logical shift fills the vacated bits with 0. This obviously reduces portability.
Interestingly, Java has introduced a new operator to handle this issue. >> is used for arithmetic shift and >>> for logical shift.
π Definition β Arithmetic shift: A bitwise shift operation that preserves the sign bit by copying it into the vacated positions on right shift. π Definition β Logical shift: A bitwise shift operation that fills vacated positions with 0 regardless of the sign.
Byte Order and Data Exchange
The order in which bytes of one word are stored is hardware dependent. In Intel architecture the lowest byte is the most significant byte while in Motorola architecture the highest byte of a word is the most significant one. This causes problems when dealing with binary data. One should therefore only use text for data exchange. One should also be aware of internationalization issues and hence should not assume ASCII as well as English.
π Definition β Byte order (endianness): The order in which bytes within a multi-byte word are stored in memory, either little-endian (least significant byte first) or big-endian (most significant byte first).
π‘ Why this matters: When exchanging binary data between Intel and Motorola systems, the bytes will be interpreted in reverse order unless special care is taken.
Alignment
The C/C++ language does not define the alignment of items within structures, classes, and unions. Data may be aligned on word or byte boundaries.
struct X {
char c;
int i;
};
Address of i could be 2, 4, or 8 from the beginning of the structure. Therefore, using pointers and then typecasting them to access individual components will cause all sorts of problems.
Bit Fields
Bit fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples:
- Packing several objects into a machine word (e.g., 1-bit flags compacted β Symbol tables in compilers)
- Reading external file formats (non-standard file formats could be read in, e.g., 9-bit integers)
C lets us do this in a structure definition by putting :bit length after the variable:
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int funny_int:9;
} pack;
Here the packed_struct contains 6 members: Four 1-bit flags f1..f3, a 4-bit type and a 9-bit funny_int.
C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, some compilers may allow memory overlap for the fields whilst others would store the next field in the next word.
Bit fields are a convenient way to express many difficult operations. However, bit fields do suffer from a lack of portability between platforms:
- Integers may be signed or unsigned
- Many compilers limit the maximum number of bits in the bit field to the size of an integer (16-bit or 32-bit varieties)
- Some bit field members are stored left to right, others are stored right to left in memory
- If bit fields are too large, the next bit field may be stored consecutively in memory (overlapping the boundary between memory locations) or in the next word of memory
Bit fields therefore should not be used.
β Key Takeaways
The most critical things a student MUST remember from this lecture for the exam are: portability requires intentional design from the start, specifically by sticking to ANSI/ISO standards and using STL rather than vendor extensions. Data type sizes (especially int varying from 2 to 4 bytes), signedness of char, and the unspecified nature of right shift operations are major sources of portability bugs. Binary data exchange between different architectures fails due to byte order differences, so text should always be used instead. Structure alignment is implementation-defined and cannot be relied upon. Finally, bit fields are highly non-portable due to compiler-dependent storage order, signedness, and size limits, and should be avoided entirely.
π§ Quick Revision Questions
- Why should you use
int cinstead ofchar cwhen callinggetchar()and checking for EOF? - What is the difference between arithmetic and logical right shift, and why does this matter for portability?
- When exchanging data between an Intel-based system and a Motorola-based system, what problem can occur with binary data and how should it be avoided?
- Why can't you reliably determine the address of member
iinstruct X { char c; int i; }across different compilers? - List four reasons why bit fields should not be used in portable code.