C Programming Expressions Statements

Last modified by Microchip on 2023/11/09 09:06

Expressions

  • Represent a single data item (e.g. character, number, etc.)
  • May consist of:
    • A single entity (a constant, variable, etc.)
    • A combination of entities connected by operators (+, -, *, /, and so on)

Examples

1
2
3
4
5
6
7
8
a + b
x = y
speed = dist/time1
z = ReadInput()
c <= 7
x == 25
count++
d = a + 5

Statements

  • Cause action to be carried out
  • Three kinds of statements in C:
    • Expression Statements
    • Compound Statements
    • Control Statements

Expression Statements

  • An expression followed by a semi-colon
  • Execution of the statement causes the expression to be evaluated

Examples

1
2
3
4
5
6
7
8
9
10
11
i = 0;                     

i++;                        

a = 5 + i;                 

y = (m * x) + b;

printf("Slope = %f", m);

Line 1 is an assignment statement. It assigns the value 0 to the variable i.

Line 3 is an incrementing statement. It increments the value of i by 1.

Line 5 is an assignment statement. It first evaluates the expression 5 + i and assigns the results to the variable a.

Line 7 is yet another assignment statement, though a bit more complex. m is multiplied by x, that result is added to b and the final result is assigned to y.

The statement on line 9 causes the printf function to be evaluated. For example, if the value of m is 5, the result would be Slope = 5 in the UART1 window.

Line 11 is an empty statement. It does nothing and is often referred to as a null statement. It makes little sense by itself but is very useful in other circumstances which we will see later on. Note that this is NOT equivalent to a nop instruction. This generates no code at all.

Compound Statements

  • A group of individual statements enclosed within a pair of curly braces, { and }
  • Individual statements within may be any statement type, including compound
  • Allows statements to be embedded within other statements
  • Does NOT end with a semicolon after }
  • Also called Block Statements

Example

1
2
3
4
5
6
7
8
9
10
{
   float start, finish;

   start = 0.0;
    finish = 400.0;
    distance = finish start;
    time1 = 55.2;
    speed = distance / time1;
    printf("Speed = %f m/s", speed);
}  

Control Statements

  • Used for loops, branches, and logical tests
  • Often require other statements embedded within them

Example

1
2
3
4
5
while (distance < 400.0)
{
   printf("Keep running!");
   distance += 0.1;
}

This statement contains a compound statement which in turn contains two expression statements. The compound statement will continue to run as long as the value of distance doesn't exceed 400.0.