C: Variables and
operators
(Textbook chapter 12)
Basic C elements
Variables
named and typed data items
Operators
predefined actions performed on data items
combined with variables to form expressions,
statements
Rules and usage
Implementation using LC-3
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-2
Data types
C has three basic data types
int
signed integer (at least 16 bits)
double floating-point number (at least 32 bits)
char
character (at least 8 bits)
Exact size can vary, depending on processor
int is supposed to be "natural" integer size;
for LC-3, that's 16 bits -- 32 bits for most
modern processors (i.e. the machines word size)
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-3
Variable names
Use any combination of letters, numbers, and
underscore ( _ )
Case matters
sum and Sum are different
Cannot begin with a number
usually, variables beginning with underscore
are used only in special library routines
Only the first 31 characters are taken into account
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-4
Examples of variable names
Legal
i
same identifier
wordsPerSecond
words_per_second
_green
aReally_longName_moreThan31chars
aReally_longName_moreThan31characters
Illegal
10sdigit
ten'sdigit
done?
double
reserved keyword
13-5
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
Literals
Integer
123
-123
0x123
/* hexadecimal */
Floating point
6.023
6.023e23
5E12
/* 6.023 x 1023 */
/* 5.0 x 1012 */
Character
'c'
'\n'
'\xA'
/* newline */
/* ASCII 10 (0xA) */
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
/* decimal */
13-6
Scope: Global and local
Where is the variable accessible?
Global: accessed anywhere in program
Local: only accessible in a particular region (block)
Compiler infers scope from where variable is
declared
programmer doesn't have to explicitly state
Variable is local to the block in which it is declared
block defined by open and closed braces { }
can access variable declared in any "containing" block
Global variables are declared outside all blocks
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-7
Structure of a C program
One main() function
A bunch of other functions
/*****************************/
main()
{
}
/*---------------------------*/
functionA()
{
}
/*---------------------------*/
functionB()
{
}
/*****************************/
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-8
Example
#include
int
<stdio.h>
itsGlobal = 0;
main()
{
int
itsLocal = 1;
/* local to main */
printf("Global %d Local %d\n", itsGlobal, itsLocal);
{
int itsLocal = 2;
/* local to this block */
itsGlobal = 4;
/* change global variable */
printf("Global %d Local %d\n", itsGlobal, itsLocal);
}
printf("Global %d Local %d\n", itsGlobal, itsLocal);
}
Output
Global 0 Local 1
Global 4 Local 2
Global 4 Local 1
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-9
Operators
Programmers manipulate variables using the operators
provided by the high-level language.
Variables and operators combine to form expressions
and statements which denote the work to be done by
the program.
Each operator may correspond to many machine
instructions.
Example: The multiply operator (*) typically
requires multiple LC-3 ADD instructions.
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-10
Expression
Any combination of variables, constants, operators,
and function calls
every expression has a type, derived from the
types of its components (according to C typing
rules)
Examples what is the type of:
counter >= STOP
x + sqrt(y)
x & z + 3 || 9 - w-- % 6
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-11
Statement
Expresses a complete unit of work
Statements are executed in sequential order
Simple statements end with a semicolon
z = x * y;
y = y + 1;
;
/* assign product to z */
/* after multiplication */
/* null statement */
Compound statements group simple statements
using braces.
syntactically equivalent to a simple statement
{
z = x * y; y = y + 1; }
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-12
Operators
Three things to know about each operator
(1) Function
what does it do?
(2) Precedence
in which order are operators combined?
Example:
a * b + c * d is the same as "(a * b) + (c * d)"
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
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-13
Assignment operator
= changes the value of a variable.
x = x + 4;
1. Evaluate right-hand side.
2. Set value of left-hand side variable to result.
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-14
Assignment operator
All expressions evaluate to a value,
even the ones with the assignment operator.
For assignment, the result is the value assigned.
usually (but not always) the value of the righthand side
type conversion might make assigned value
different than computed value
Assignment associates right to left.
y = x = 3;
y gets the value 3, because (x = 3) evaluates to the
value 3.
13-15
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
Arithmetic operators
Symbol Operation
*
multiply
/
divide
%
modulo
+
addition
subtraction
Usage
x * y
x / y
x % y
x + y
x - y
Precedence
Assoc
l-to-r
l-to-r
l-to-r
l-to-r
l-to-r
All associate left to right.
* / % have higher precedence than + - (here lower
numbers mean higher precedence)
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-16
Arithmetic expressions
If mixed types, smaller type is "promoted" to larger.
x + 4.3
if x is int, is converted to double and result is double
Integer division -- fraction is dropped.
x / 3
if x is int and x=5, result is 1 (not 1.666666...)
Modulo -- result is remainder.
x % 3
if x is int and x=5, result is 2.
13-17
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
Bitwise logic operators
Symbol Operation
~
bitwise NOT
&
bitwise AND
^
bitwise XOR
|
bitwise OR
Usage
~x
x & y
x ^ y
x | y
Precedence
Assoc
r-to-l
11
l-to-r
12
l-to-r
13
l-to-r
Operate on variables bit-by-bit.
Like LC-3 AND and NOT instructions.
Shift operations are logical (not arithmetic).
Operate on values -- neither operand is changed.
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-18
Shift operators
Symbol Operation
<<
left shift
>>
right shift
Usage
x << y
x >> y
Precedence
Assoc
l-to-r
l-to-r
One kind of left shift: shift 0 into the lsb. Ex:
Two kinds of right shifts:
Logic: shift 0 into the MSb. Used with unsigned types
Arithmetic: sign-extend the MSb. Used with signed
types
13-19
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
Boolean logic operators
Symbol
!
&&
||
Operation
logical NOT
logical AND
logical OR
Usage
!x
x && y
x || y
Precedence Assoc
4
r-to-l
14
l-to-r
15
l-to-r
Treats entire variable (or value)
as TRUE (non-zero) or FALSE (zero).
Result is 1 (TRUE) or 0 (FALSE).
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-20
10
Relational operators
Symbol
Operation
>
greater than
>=
greater than or equal
<
less than
<=
less than or equal
==
equal
!=
not equal
Usage PrecedenceAssoc
x > y
9
l-to-r
x >= y
9
l-to-r
x < y
9
l-to-r
x <= y
9
l-to-r
x == y
10
l-to-r
x != y
10
l-to-r
Result is 1 (TRUE) or 0 (FALSE).
Note: Don't confuse equality (==) with assignment (=).
13-21
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
Special operators: ++ and - Changes value of variable before (or after)
its value is used in an expression.
Symbol
Operation
++
postincrement
-postdecrement
++
preincrement
-predecrement
Usage
x++
x-++x
--x
Precedence Assoc
2
r-to-l
r-to-l
r-to-l
r-to-l
Pre: Increment/decrement variable before using its value.
Post: Increment/decrement variable after using its value.
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-22
11
Using ++ and -x = 4;
y = x++;
Results: x = 5, y = 4
(because x is incremented after assignment)
x = 4;
y = ++x;
Results: x = 5, y = 5
(because x is incremented before assignment)
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-23
Care with ++ and -What does this code print?
int
a, b;
a = b = 0;
a = ++b + b;
printf(%d %d, a, b);
The value of a is machine-dependent - bad coding practice. Use
instead:
++b;
a = b + b;
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-24
12
Practice with precedence
Assume a=1, b=2, c=3, d=4.
x = a * b + c * d / 2;
/* x = 8 */
same as:
x = (a * b) + ((c * d) / 2);
For long or confusing expressions,
use parentheses, because the reader (or you!)
might not have memorized precedence table.
Note: Assignment operator has lowest precedence,
so all the arithmetic operations on the right-hand side
are evaluated first.
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-25
Special operators: +=, *=, etc.
Arithmetic and bitwise operators can be combined
with the assignment operator.
Statement
Equivalent assignment
x += y;
x = x + y;
x -= y;
x = x - y;
All have same
x *= y;
x = x * y;
precedence and
x /= y;
x = x / y;
associativity
as =
x %= y;
x = x % y;
and associate
x &= y;
x = x & y;
right-to-left.
x |= y;
x = x | y;
x ^= y;
x = x ^ y;
x <<= y;
x = x << y;
x >>= y;
x = x >> y;
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-26
13
Special operator: Conditional
Symbol
?:
Operation
conditional
Usage
x ? y : z
Precedence Assoc
16
l-to-r
If x is TRUE (non-zero), result is y;
else, result is z.
Like a MUX, with x as the select signal.
y
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-27
Recommended exercises
Ex 12.2, 12.3
Ex 12.5, 12.6, 12.7, 12.9, 12.11, 12.13, 12.16, 12.17
all good review of operators
Ex. 12.8, 12.10, and 12.19 all good simple starting
programs
Ex 12.20 good too, slightly harder
CMPE12 Fall 2006 A. Di Blas (Orig. by C. Bazeghi)
13-28
14