COMP2521 20T1 ♢ Programming Style

COMP2521 20T2 ♢ Style ♢ [0/19]
❖ COMP1511 Style


Required use of a restricted subset of C:

But ... this style is not used in texts or real code.
COMP2521 20T2 ♢ Style ♢ [1/19]
❖ COMP2521 Style


Extends the range of allowed constructs:

Some things will not change:
* unless the variable is an array index and/or used in a very limited scope
COMP2521 20T2 ♢ Style ♢ [2/19]
❖ Poor Style

Examples of poor style:

int fff(int n)
{
 int flab = 1;
   if (n < 1) return -1;
      for (int z = 1; z <= n; z++)
      flab = flab * z;
  return flab;
}

int ff(int n) {
int f = 1;  if (n < 1) return -1;
for (int xy = 1; xy <= n; xy++) f *= xy;
return f; }

COMP2521 20T2 ♢ Style ♢ [3/19]
❖ Comments


COMP1511 used (exclusively?) /*...*/ comments

Many books, code-bases use //... comments

Either is ok, but prefer

(and C doesn't support #... style, since # used for e.g. #include)
COMP2521 20T2 ♢ Style ♢ [4/19]
❖ Use of Brackets

Put control-group start bracket after conditional expression

Can omit brackets if control structure owns a single statement

Examples:


if (x > 0) {         |   while (*c != '\0') {
   y = y * x;        |      c++;
}                    |   } 
                     | 
or
                     | 
if (x > 0)           |   while (*c != '\0') 
   y = y * x;        |      c++;
                     | 
or even (slightly naughty)
                     | 
if (x > 0) y *= x;   |   while (*c != '\0') c++;

COMP2521 20T2 ♢ Style ♢ [5/19]
❖ ... Use of Brackets

If condition followed by return, continue, break, use one line, e.g.


// handle incorrect parameter
if (x < 0) return -1;

// early exit from loop
for (c = str; *c != '\0'; c++) {
    if (*c == 'z') break;
    ... process next char in string ...
}

// ignore spaces in string
for (c = str; *c != '\0'; c++) {
    if (isspace(*c)) continue;
    ... process non-space char ...
}

COMP2521 20T2 ♢ Style ♢ [6/19]
❖ ... Use of Brackets

Can put function start bracket on line after function header, e.g.


int myFun(parameters) {
   ... function body ...
}
or

int myFun(parameters)
{
   ... function body ...
}
or

int
myFun(parameters) {  // name at start of line
   ... function body ...
}

COMP2521 20T2 ♢ Style ♢ [7/19]
❖ Assignment in Expressions

Can use assignment statements in expressions, e.g.

// assign same value to multiple variables
i = j = k = 0;
or
i = (j = (k = 0));
or
k = 0; j = 0; i = 0;

// scan stdin, char-by-char
while ((ch = getchar()) != EOF) {
    ...process next char...
}

but you should try to minimse their use in this way

COMP2521 20T2 ♢ Style ♢ [8/19]
❖ Conditional Expressions


Conditional expressions return a value, based on a test

Handle a moderately common practical case:

if (x > 0)
    y = x + 1;
else
    y = 0;

can be expressed as

y = (x > 0) ? x+1 : 0;

Requires: same variable in both if branches; one statement in each branch.

COMP2521 20T2 ♢ Style ♢ [9/19]
❖ Control Structures

Can use more C control structures

COMP2521 20T2 ♢ Style ♢ [10/19]
❖ Switch-statements

switch encapsulates a common selection:

if (v == C1) {
   S1;
} else if (v == C2) {
   S2;
}
...
else if (v == Cn) {
   Sn;
}
else {
   Sn+1;
}

COMP2521 20T2 ♢ Style ♢ [11/19]
❖ ... Switch-statements

Multi-way if becomes:

switch (v) {
case C1:
   S1; break;
case C2:
   S2; break;
...
case Cn:
   Sn; break;
default:
   Sn+1;
}

Note: break is critical; if not present, falls through to next case.

COMP2521 20T2 ♢ Style ♢ [12/19]
❖ ... Switch-statements

Example of "fall-through" (when break absent):


switch (ch) {
case 'a': printf("a\n");
case 'b': printf("b\n"); break;
case 'c': printf("c\n"); break;
case 'd': printf("d\n");
default:  printf("?"); // break optional here
}

COMP2521 20T2 ♢ Style ♢ [13/19]
❖ For-loops

for encapsulates a common loop pattern:

initialise;
while (Continuation) {
   do stuff;
   increment;
}

as

for (initialise; Continuation; increment) {
   do stuff;
}

COMP2521 20T2 ♢ Style ♢ [14/19]
break and continue

These constructs affect how a loop operates, e.g.

while (Continuation) {
   ... do stuff1 ... 
   if (Test1) continue;
   ... do stuff2 ... 
   if (Test2) break;
   ... do stuff3 ... 
}

COMP2521 20T2 ♢ Style ♢ [15/19]
❖ Functions and return


COMP1511 and "proper" style suggest that ...

Pragmatically, multiple returns can be useful to ...
COMP2521 20T2 ♢ Style ♢ [16/19]
❖ ... Functions and return

Example:  compute n!;  return -1 if error;  no overflow check


int factorial(int n)
{
   int fac = 1;
   if (n < 1) return -1;  // error return
   for (int i = 1; i <= n; i++) {
      fac = fac * i;
   }
   return fac;  // return result
}

int factorial(int n)
{
   if (n < 1) return -1;
   else if (n == 1) return 1;
   else return n * factorial(n-1);
}

COMP2521 20T2 ♢ Style ♢ [17/19]
❖ ... Functions and return

Example: search for key in array a[] of length n


int search(int key, int a[], int n)
{
   int where = -1; // not found value
   for (int i = 0; i < n; i++) {
      if (a[i] == key) where = i;
   }
   return where;  // return result or not found
}

 or 

int search(int key, int a[], int n)
{
   for (int i = 0; i < n; i++) {
      if (a[i] == key) return i;  // return result
   }
   return -1;  // not found value 
}

COMP2521 20T2 ♢ Style ♢ [18/19]
❖ Relaxed Style


Good: gives you more freedom and power

Bad: gives you more freedom and power So, you must still use some discipline.
COMP2521 20T2 ♢ Style ♢ [19/19]


Produced: 1 Jun 2020