Basic C Elements
Variables
• named, typed data items
Operators
Chapter 6 • predefined actions performed on data items
• combined with variables to form expressions, statements
Variables and
Operators Rules and usage
Implementation using LC-3
12-2
Data Types Variable Names
C has three basic data types Any combination of letters, numbers, and underscore (_)
char character (8 bits) Case matters
int integer (16 – 32 bits) • "sum" is different than "Sum"
float floating point (32 bits)
double floating point (64 bits) Cannot begin with a number
• usually, variables beginning with underscore
are used only in special library routines
Exact size can vary, depending on processor
With some compiler like Borland C++, only first 31/55
• int is supposed to be "natural" integer size;
characters are used
for LC-3, that's 16 bits -- 32 bits for most modern processors
12-3 12-4
1
Examples Literals
Legal Integer
i 123 /* decimal */
wordsPerSecond same identifier
-123
words_per_second
_green 0x123 /* hexadecimal */
aReally_longName_moreThan31chars Floating point
aReally_longName_moreThan31characters
6.023
6.023e23 /* 6.023 x 1023 */
Illegal
5E12 /* 5.0 x 1012 */
10sdigit
ten'sdigit Character
done? reserved keyword 'c'
double
'\n' /* newline */
'\xA' /* ASCII 10 (0xA) */
12-5 12-6
Some escape sequences of characters Scope: Global and Local
\a 0x07 BEL Where is the variable accessible?
\b 0x08 BS Global: accessed anywhere in program
\f 0x0C FF Local: only accessible in a particular region
\n 0x0A LF
\r 0x0D CR Compiler infers scope from where variable is declared
\t 0x09 HT • programmer doesn't have to explicitly state
\v 0x0B VT
\\ 0x5C \
Variable is local to the block in which it is declared
\' 0x2C '
• block defined by open and closed braces { }
\" 0x22 " • can access variable declared in any "containing" block
\? 0x3F ?
\ddd ddd Base-8 ASCII code
Global variable is declared outside all blocks
\xHH 0 x HH Base-16 ASCII code
12-7 12-8
2
Example Operators
#include <stdio.h>
int itsGlobal = 0;
Programmers manipulate variables
using the operators provided by the high-level language.
main()
{
int itsLocal = 1; /* local to main */ Variables and operators combine to form
printf("Global %d Local %d\n", itsGlobal, itsLocal); expressions and statements
{
int itsLocal = 2; /* local to this block */ which denote the work to be done by the program.
itsGlobal = 4; /* change global variable */
printf("Global %d Local %d\n", itsGlobal, itsLocal);
} Each operator may correspond to many
printf("Global %d Local %d\n", itsGlobal, itsLocal); machine instructions.
}
• Example: The multiply operator (*) typically requires
multiple LC-3 ADD instructions.
Output
Global 0 Local 1
Global 4 Local 2
Global 4 Local 1
12-9 12-10
Expression Statement
Any combination of variables, constants, operators, Expresses a complete unit of work
and function calls • executed in sequential order
• every expression has a type,
derived from the types of its components
(according to C typing rules) Simple statement ends with semicolon
z = x * y; /* assign product to z */
Examples: y = y + 1; /* after multiplication */
counter >= STOP ; /* null statement */
x + sqrt(y)
x & z + 3 || 9 - w-- % 6 Compound statement groups simple statements
using braces.
• syntactically equivalent to a simple statement
{ z = x * y; y = y + 1; }
12-11 12-12
3
Operators Assignment Operator
Three things to know about each operator Changes the value of a variable.
(1) Function
• what does it do? x = x + 4;
(2) Precedence
• in which order are operators combined?
1. Evaluate right-hand side.
• Example:
"a * b + c * d" is the same as "(a * b) + (c * d)" 2. Set value of left-hand side variable to result.
because multiply (*) has a higher precedence than addition (+)
(3) Associativity
• in which order are operators of the same precedence combined?
• Example:
"a - b - c" is the same as "(a - b) - c"
because add/sub associate left-to-right
12-13 12-14
Assignment Operator Arithmetic Operators
All expressions evaluate to a value, Symbol Operation Usage Precedence Assoc
even ones with the assignment operator. * multiply x * y 6 l-to-r
/ divide x / y 6 l-to-r
For assignment, the result is the value assigned. % modulo x % y 6 l-to-r
• usually (but not always) the value of the right-hand side + addition x + y 7 l-to-r
type conversion might make assigned value
different than computed value - subtraction x - y 7 l-to-r
Assignment associates right to left. All associate left to right.
y = x = 3; * / % have higher precedence than + -.
y gets the value 3, because (x = 3) evaluates to the value 3.
12-15 12-16
4
Arithmetic Expressions Bitwise Operators
If mixed types, smaller type is "promoted" to larger. Symbol Operation Usage Precedence Assoc
x + 4.3 ~ bitwise NOT ~x 4 r-to-l
if x is int, converted to double and result is double << left shift x << y 8 l-to-r
>> right shift x >> y 8 l-to-r
Integer division -- fraction is dropped. & bitwise AND x & y 11 l-to-r
x / 3 ^ bitwise XOR x ^ y 12 l-to-r
if x is int and x=5, result is 1 (not 1.666666...) | bitwise OR x | y 13 l-to-r
Operate on variables bit-by-bit.
Modulo -- result is remainder.
• Like LC-3 AND and NOT instructions.
x % 3 Shift operations are logical (not arithmetic).
if x is int and x=5, result is 2. Operate on values -- neither operand is changed.
12-17 12-18
Logical Operators Examples
Symbol Operation Usage Precedence Assoc 1. if ( !a)
! logical NOT !x 4 r-to-l
// a = 0
&& logical AND x && y 14 l-to-r
|| logical OR x || y 15 l-to-r
2. if (a % 2 == 0)
Treats entire variable (or value) -> if ( ! (a % 2 ) )
as TRUE (non-zero) or FALSE (zero).
3. if (c >= ‘a’ && c <= ‘z’ || c >= ‘A’ && c <= ‘Z’)
Result is 1 (TRUE) or 0 (FALSE).
// ?
12-19 12-20
5
Example How about this,
Input a character, check if it is a letter or not Input a character, check if it is NOT a letter
int c; int c;
c = getchar (); c = getchar ();
if (c >= ‘a’ && c <= ‘z’ || c >= ‘A’ && c <= ‘Z’) if (? )
printf (“%c is a letter”, c); printf (“%c is NOT a letter”, c);
12-21 12-22
Relational Operators Special Operators: ++ and --
Symbol Operation Usage Precedence Assoc Changes value of variable before (or after)
> greater than x > y 9 l-to-r its value is used in an expression.
>= greater than or equal x >= y 9 l-to-r
< less than x < y 9 l-to-r Symbol Operation Usage Precedence Assoc
<= less than or equal x <= y 9 l-to-r ++ postincrement x++ 2 r-to-l
== equal x == y 10 l-to-r -- postdecrement x-- 2 r-to-l
!= not equal x != y 10 l-to-r ++ preincrement ++x 3 r-to-l
-- predecrement --x 3 r-to-l
Result is 1 (TRUE) or 0 (FALSE).
Pre: Increment/decrement variable before using its value.
Post: Increment/decrement variable after using its value.
Note: Don't confuse equality (==) with assignment (=).
12-23 12-24
6
Using ++ and -- Practice with Precedence
Assume a=1, b=2, c=3, d=4.
x = 4;
y = x++; x = a * b + c * d / 2; /* x = 8 */
Results: x = 5, y = 4 same as:
(because x is incremented after assignment) x = (a * b) + ((c * d) / 2);
x = 4; For long or confusing expressions,
y = ++x; use parentheses, because reader might not have
Results: x = 5, y = 5 memorized precedence table.
(because x is incremented before assignment)
Note: Assignment operator has lowest precedence,
so all the arithmetic operations on the right-hand side
are evaluated first.
12-25 12-26
Variables and Memory Locations Example:
#include <stdio.h>
In our examples, int inGlobal;
a variable is always stored in memory.
main()
{
int inLocal; /* local to main */
When assigning to a variable, int outLocalA;
must store to memory location. int outLocalB;
/* initialize */
inLocal = 5;
A real compiler would perform code optimizations inGlobal = 3;
that try to keep variables allocated in registers.
/* perform calculations */
Why? outLocalA = inLocal++ & ~inGlobal;
outLocalB = (inLocal + inGlobal) - (inLocal - inGlobal);
/* print results */
printf("The results are: outLocalA = %d, outLocalB = %d\n",
outLocalA, outLocalB);
}
12-27 12-28
7
Special Operator: Conditional Example
Symbol Operation Usage Precedence Assoc
?: conditional x?y:z 16 l-to-r If statement:
if (a ==5)
If x is TRUE (non-zero), result is y; b = 2;
else, result is z. else
b = 4;
Like a MUX, with x as the select signal.
Conditional expresion:
y z
b = (a == 5) ? 2 : 4;
1 0
x
12-29 12-30
Comma operator Homework
(value 1) , (value 2)
12.1 -> 12.20
Example:
1. a = 2;
b = (2 , a + 1);
2. for (i =1, s = 0; i < n; i++)
...
12-31 12-32