Common Features of C Based Languages

From SwinBrain

The C programming language provides the basis for a number of other programming languages such as C++, C#, Objective C, and Java. This article presents some of the common programming constructs shared between these languages. The accompanying video podcast on iTunes U demonstrates the creation of a small C program using SwinGame to draw shapes to the screen. The code that created for this podcast is available for download here.

Contents

Basic Rules

C based languages usually have the following basic rules:

  • The language is case sensitive: Hello and hello are distinct identifiers.
  • Each statement is terminated by a semicolon (;)
  • Statements can be grouped together into blocks using braces { ... }
  • Functions can return values using the return keyword which accepts the returned value (if any) and returns execution to the caller.
  • Single line comments start with //
  • Multi-line comments start with /* .... and end with ... */
  • There is no standard boolean type. In C false is considered to be anything that evaluates to a 0 value and true is any non-zero value. To check if something is "true" you need to check if it is not equal to 0 (a != 0).

Variable Declarations

C style languages typically support the following data types:

  • int, short, long
  • float, double
  • char
  • void

Variables in these languages are declared as:

<type> <variable name>

The following code demonstrates the creation of several variables. Arrays are declared using [] after the type which is also used to index values in the array.

  1. int age;
  2. float result;
  3. char[] name;
  4. int[] scores;

String Data

Standard C does not have a string type (though the different variants usually add this feature). In C a string is an array of characters (char[] name), or a Pointer to the first character in the string. In either case the end of a C string is identified by a null character (the character with ASCII Character Code 0). The C based languages inherit C's string metalanguage. In C the back slash (\) is a meta-character indicating that the following character has a different meaning to its literal form. The following table illustrates the common C meta-characters.

C Metacharacters
Character Combination Meaning Character Code Example Usage Example Output
\n New Line 10 "Hello\nWorld" Hello
World
\r Carriage Return 13 "Hello\r\nWorld" (Windows newline) Hello
World
\t Tab 38 "Hello\tWorld" Hello       World
\' Single Quote 39 "Hello \'World\'" Hello 'World'
\" Double Quote 34 "Hello \"World\"" Hello "World"
\\ Backslash 92 "Hello \\ World" Hello \ World


Output

Terminal output can be generated using the printf function. For details on this function see printf at cplusplus.com

Mathematical Operators

Kind Operator Example Details
Multiplication * a * b
Division / a / b Division does not automatically convert integers to floats, so 1 /2 = 0 not 0.5. To perform floating point division ensure that at least one of the operands is a floating point value, e.g. 1 / 2.0f = 0.5f; and 1.0 / 2.0 = 0.5.
Modulo % a % b The remainder after integer division.
Addition + a + b
Subtraction - a - b
Pre-increment ++ a = ++c + b; Increment the value of the variable then use the new value. In this example if c and b start with the value 1, the value 3 will be stored in a and c will end with the value 2. Can also be used to just increment the value of a variable e.g. ++i;.
Post-increment ++ a = c++ + b; Increment the value of the variable after using the current value. In this example if c and b start with the value 1, the value 2 will be stored in a and c will end with the value 2. Can also be used to just increment the value of a variable e.g. i++;.
Pre-decrement -- a = --c + b; Decrement the value of the variable then use the new value. In this example if c and b start with the value 1, the value 1 will be stored in a and c will end with the value 0. Can also be used to just decrement the value of a variable e.g. i--;.
Post-decrement -- a = c-- + b; Decrement the value of the variable after using the current value. In this example if c and b start with the value 1, the value 2 will be stored in a and c will end with the value 0. Can also be used to just decrement the value of a variable e.g. --i;.
Grouping (...) a = (b + c) * d; You can control the order of evaluation using brackets.


Assignments

In C assignment is an Expression, allowing it to be used in a variety of contexts. The value of the expression is the value being assigned to the variable.

  • Assignment's can be chained together. The following code assigns the value 5 to variables a,b, and c.
a = b = c = 5;
  • Assignment can be used (possibly mistakenly) in conditions. The following code assigns the value in b to the variable a. If b is a non-zero value then this expression is true.
if (a = b) // is not the same as if (a == b) ... 
  • The following code assigns the value in variable c to variable b and then checks if this value is equal to the value in a.
if (a == (b = c)) ...

Assignment operators
Kind Operator Example Details
= a = b + c; A single equals sign is used to assign the right hand value to the variable on the left hand side. In this example the value of b + c is assigned to the variable a. Increment by
+= a += b + c; The plus and equals sign are used to increment the left had side by the value of the right hand side. In this example a is give the value a + (b + c). Decrement by
-= a -= b + c; The minus and equals sign are used to decrement the left had side by the value of the right hand side. In this example a is give the value a - (b + c). Multiply by
= a *= b + c; The asterisk and equals sign are used to multiply the left had side by the value of the right hand side. In this example a is give the value a * (b + c). Divide by
/= a /= b + c; The forward slash and equals sign are used to divide the left had side by the value of the right hand side. In this example a is give the value a / (b + c).  


Logic, Comparison, and Equality

Comparison operators
Kind Operator Example Details
Equality == a == b + c Two equals signs indicates an equality comparison. In this example the result will be true if a is equal to b + c.
Inequality != a != b + c The exclamation equal indicated an inequality comparison. In this example the result will be false if a is equal to b + c.
Less Than < a < b + c The left pointing angle bracket indicates a less than comparison. In this example the result is true if a is less than (but not equal to) b + c.
Less Than Or Equal <= a <= b + c The left pointing angle bracket followed by equal indicates a less than or equal comparison. In this example the result is true if a is less than or equal to b + c.
Greater Than > a > b + c The right pointing angle bracket indicates a greater than comparison. In this example the result is true if a is larger than (but not equal to) b + c.
Greater Than Or Equal >= a >= b + c The right pointing angle bracket followed by equal indicates a greater than or equal comparison. In this example the result is true if a is larger than or equal to b + c.

Logical Operators
Kind Operator Example Details
Not ! a = ! b; The exclamation sign indicates the logical not. In this example a is assigned true when b is false (a = not b).
Logical And && a && b The double ampersand is used to indicate logical and. In this example the result is true if both a and b are true, otherwise the result is false.
Logical Or || a || b The double vertical bar is used to indicate logical or. In this example the result is true if a or b is true or if both are true.

Bitwise Operators

Bitwise Operators
Kind Operator Example Details
Bitwise And & a = b & c; A single ampersand represents bitwise and. In this example the result of anding the bits in b with c is stored in a, resulting in a having the bits that are commonly set in both b and c.
Bitwise Or | a = b | c; A single vertical bar is used to represent bitwise or. In this example the result of or'ing the bits in b with c is stored in a, resulting in the a storing all the set bits from both b and c.
Shift Left << a = b << 1 Two left angle brackets indicates a shift left. The example shows a being assigned the value of the bits in b shifted left one position (multiply by 2).
Shift Right >> a = b >> 1 Two right angle brackets indicates a shift right. The example shows a being assigned the value of the bits in b shifted right one position (divide by 2).


Basic Statements

The C language is a Procedural Programming language. It includes code to allow Statements to be grouped together into a compound statement, Branching Statements and Looping Statements to control the sequencing of instructions. It also contains a number of Control Flow Statements that relax the strict one entry = one exit rules of Structured Programming to allow greater flexibility with the flow of control in c programs. Basic outlines of each of these is presented below.

Grouping

The block statement allows multiple statements to be grouped as a single statement. This is often used with other kinds of statements to allow multiple actions to be performed within a loop or branch.

{ [statements] }

Example usage: The following code illustrates code that groups together multiple statements within an if statement.

if ( strcmp(name, "Fred") ) //if name equals "Fred"
{
    printf("Hello Fred!\n");
    printf("I hope you are having a good day....");
}

Branching Statements

There are two kinds of branching statements common to C languages. These are the if statement and the switch statement (also know as the case statement).

If statement allows code to be executed based upon a condition. In C languages the condition controlling the branches is enclosed in brackets, rather than using then or a similar identifier to indicate the end of the condition such as in Pascal or Visual Basic. There is also no else if construct built into in the language, though the else branch can contain an if statement to achieve the same effect. In C the true body and the false body are single statements. Multiple actions can be performed here through the use of a block (grouping) statement.

if(<condition>) <true body> [else <false body>]

Example usage: The following example demonstrates the use of a block within the else branch of an if statement.

if(myAge < 10) 
    return 1;
else
{
    //something else...
    return 0;
}

The following example slows an else-if style structure by nesting an if statement within the else branch.

if(myAge < 10) 
    return 1;
else if (myAge < 20)
    return 0;
else if (myAge < 30)
    return 1;
else
    return 0;


The switch (or case) statement can be used to provide a set of options. With the switch statement the value of an expression is used to select the branch with the matching case value. In C the expression in the switch statement must be an ordinal type (char, integer, or enumeration), it does not work with strings or floating point values. Control flow within the switch statement must be managed by the developer. Control jumps to the start of the case with the value that matches the expression, and continues from there. If no control flow statement is encountered the flow continues from there entering the subsequent case bodies. If you only want the one case branch to execute you need to break out of the switch statement at the end of the case.

switch([variable])
{
   [case <value>: [matching body] [break;]]
   [case <value>: [matching body] [break;]]
   [case ...]
   [default: [default body] [break;]]
}

Example usage: The following example illustrates a basic switch statement with each case terminating:

int age;
 
switch(age) //first character of name.
{
    case 10:
         printf("Welcome to double digits!\n");
         break;
    case 20:
        printf("Your teens are over...\n");
        break;
    default:
        printf("Bah... ok...\n");
        break;
}

The following example allows control to drop through several cases to reach some common processing.

char c = ...;
switch(c)
{
   case 'a':
   case 'b':
   case 'c':
   case 'd':
   case 'e':
   case 'f': 
        v = hexValOf(c); 
        break;
   case '0':
   case '1':
   case '2':
   case '3':
   case '4':
   case '5':
   case '6':
   case '7':
   case '8':
   case '9': 
        v = intValOf(c);
        break;
   default: return -1;
}

Looping Statements

The looping statements allow code to be repeated a number of times. C includes the standard pre-condition, post-condition and for loop variants.

The do ... while statement allows code to be repeated 1 or more times as the condition is evaluated at the end of the loop. Like the if statement, the do while loop executes only a single statement and the block statement must be used to group multiple statements together if this is required.

do <body> while(<condition>);

Example usage: The following loop ensures that the game loop is executed at least once.

do
{
    processEvents();
    clearScreen();
    refreshScreen();
} while( windowCloseRequested() == 0 );

The while loop allows code to be repeated 0 or more times, with the condition checked prior to the body of the loop. Like its do while counterpart, the while loop takes a single statement as its body and the block statement must be used to group multiple statements together.

while(<condition>) <body>

Example usage: The following loop reduces i to 0.

while (i > 0) i--;


The last looping statement is the for loop, which is typically used to repeat a statement a fixed number of times. In C the for loop provides three sections.

  1. The initialiser is executed on entry to the for loop.
  2. The condition is evaluated as a pre-condition loop (while...)
  3. Finally the incrementer is called at the end of each loop before the condition is re-evaluated.
for([initialiser];[condition];[incrementer]) <body>

Example usage: The following is the standard use of a for loop. It 'reads' - for i is an integer starting at 0, while i is less than 10, increment i at the end of each loop, and perform ... as the loop body.

for(int i = 0; i < 10; i++) printf("%d", i);

The following counts back from 10. It 'reads' - for i is an integer starting at 10, while i > 0, decrement i at the end of each loop, and perform ... as the loop body. The example also shows the use of a block statment, though it contains only a single statement.

for(int i = 10; i > 0; i--)
{
    printf("%d", i);
}

The following is an infinite loop (the most efficient version of an infinite loop in C):

for(;;)
{
    ...
}

Control Flow Statements

C includes a number of control flow statements that allow you to alter the sequence of its execution. These include the return, break, and continue statements.

The return statement exits the current function or procedure. When a non-void return value is required the return statement must be used to indicate the value being returned.

return [value];

Example usage: The following function return the floating point division of its integer parameters.

float divide(int a, int b)
{
    return (float)a / (float)b;
    //execution cannot reach this point as return causes the function to exit.
}

The break statement is used to exit a looping or switch statement.

break;

The continue statement is used to terminate the current iteration of a loop, but does not terminate the loop entirely.

continue;


Example usage: The following code illustrates a for loop that prints every even integer until 11 is reached. Notice that it is valid to have for loops which don't perform actions in some or all of its sections.

for(int i = 0; ; i++)
{
    if ( i == 11 ) break; // quit the loop entirely when i equals 11
    if ( i % 2 == 1 ) continue; // quit this run of the loop when i is not even
    printf("%d", i);
}

Methods, Functions and Procedures

Methods, Functions and Procedures are declared in the following form.

<return type> <name identifier>([parameter list]) { [statements] }

If the method returns no data the return type is set to void. The parameter list is a list of comma separated variable declarations (e.g. int a, int b, float c), when called the caller must provide a value for each of these parameters. Each function/procedure/method can contain a number of statements, each terminated by a semicolon (;).

Functions/procedures/methods can be called using their name identifier followed by the argument values enclosed within brackets (e.g. name(args)). When the called code has no parameters the brackets are still required (e.g. name()).

Examples follow:

  1. int getAge(Person p) { ... } //Function accepting a Person parameter and returning a string
  2. void setAge(int newAge) { ... } //Procedure accepting an int parameter
  3. float calcDivision(int a, int b) { return a / b; } //A function accepting two int parameters, and returning a float

Pointers

Pointers are used heavily in C to refer to dynamically allocated memory for things strings, dynamic arrays, and other data structures. The other C based languages have different levels of access to pointer types. The Pointers page provides an overview of working with Pointers in the C language.

  • Java has no direct way of working with pointers. All objects in Java are accessed by pointers, but the programmer has no access to this. Java uses the idea of Value and Reference Types to avoid the need for direct pointer use.
  • In C# it is possible to use pointers in unsafe code blocks, but their use is typically not required. Like Java, C# uses the idea of Value and Reference Types to avoid the need for direct pointer use.
  • C++ and Objective C both make extensive use of pointers. In Objective C all objects should be stored and accessed via pointers. C++ uses pointers, but also has the idea of References, via which the compiler manages pointer use.

Type Declarations

In C you can declare a number of different kinds of types. These include Structs and Enums. To assign these types names in C you need to use a Typedef. The ability to create these types in C based languages differs, as the following list explains.

  • Java does not have the ability to define any of the C like types. Java provides its own type declarations using classes.
  • C# allows the declaration of both structs and enums, but does not require the use of typedef to assign names to these declarations. In C# a struct is a value type.
  • C++ and Objective C both allow the use of typedefs and the declarations of structs and enums.

Struct

A struct in c allows the declaration of a record like structure. Struct is used to create composite[1] data type.

An illustration of a struct.


The following example illustrates the declaration and use of the record (struct) types shown in the above illustration.

typedef struct address_struct
{
    int no;
    char *street;
    char *suburb;
} address;
 
typedef struct person_struct
{
    char *name;
    address address;
} person;
 
int main()
{
    person myFriend;
    myFriend.name = "Fred";
    myFriend.address.no = 10;
    myFriend.address.street = "Burwood Rd";
    myFriend.address.suburb = "Hawthorn";
 
   printf("Hello %s", myFriend.name);
}

Enum

An enumerated type (enum) is a data abstraction representing a list of related constants.

typedef enum font_alignment_enum = { alignLeft, alignRight, alignCenter } font_alignment;
 
void drawText(char *txt, font_alignment align) { ... }
 
int main()
{
    font_alignment fa = alignRight;
    drawText("Hello World", fa);
    drawText("Hello World", alignLeft);
}

Typedef

A Typedef in C allows you to declare a 'friendly' name for your declared data types. The following code illustrates the examples above without the typedef. In each case you need to indicate the kind of type in its usage. Using typedef removes the need to do this as the typedef maps struct person_struct to person, for example.

struct address
{
    int no;
    char *street;
    char *suburb;
};
 
struct person
{
    char *name;
    struct address address;
};
 
int main()
{
    struct person myFriend;
    myFriend.name = "Fred";
    myFriend.address.no = 10;
    myFriend.address.street = "Burwood Rd";
    myFriend.address.suburb = "Hawthorn";
 
   printf("Hello %s", myFriend.name);
   return 0;
}
enum font_alignment = { alignLeft, alignRight, alignCenter };
 
void drawText(char *txt, enum font_alignment align) { ... }
 
int main()
{
    enum font_alignment fa = alignRight;
    drawText("Hello World", fa);
    drawText("Hello World", alignLeft);
    return 0;
}
Note: C# does not use typedef. The code struct Person { ... } in C# is the same as typedef struct person_struct { } Person; in C.

[edit]Links: Topic Brains
Return to Swin Brain