KEMBAR78
Ch06 - Variables - Operations | PDF | Integer (Computer Science) | Multiplication
0% found this document useful (0 votes)
14 views32 pages

Ch06 - Variables - Operations

Chapter 6 covers the basics of variables and operators in C programming, including data types, variable naming conventions, and the scope of variables. It explains various operators such as arithmetic, bitwise, logical, and relational operators, along with their precedence and associativity. Additionally, the chapter discusses expressions, statements, and special operators like conditional and comma operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views32 pages

Ch06 - Variables - Operations

Chapter 6 covers the basics of variables and operators in C programming, including data types, variable naming conventions, and the scope of variables. It explains various operators such as arithmetic, bitwise, logical, and relational operators, along with their precedence and associativity. Additionally, the chapter discusses expressions, statements, and special operators like conditional and comma operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Chapter 6

Variables and
Operators
Basic C Elements
Variables
• named, typed data items
Operators
• predefined actions performed on data items
• combined with variables to form expressions, statements

Rules and usage


Implementation using LC-3

12-2
Data Types
C has three basic data types

char character (8 bits)


int integer (16 – 32 bits)
float floating point (32 bits)
double floating point (64 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

12-3
Variable Names
Any combination of letters, numbers, and underscore (_)

Case matters
• "sum" is different than "Sum"

Cannot begin with a number


• usually, variables beginning with underscore
are used only in special library routines

With some compiler like Borland C++, only first 31/55


characters are used

12-4
Examples
Legal
i
wordsPerSecond same identifier
words_per_second
_green
aReally_longName_moreThan31chars
aReally_longName_moreThan31characters

Illegal
10sdigit
ten'sdigit
done? reserved keyword
double

12-5
Literals
Integer
123 /* decimal */
-123
0x123 /* hexadecimal */
Floating point
6.023
6.023e23 /* 6.023 x 1023 */
5E12 /* 5.0 x 1012 */
Character
'c'
'\n' /* newline */
'\xA' /* ASCII 10 (0xA) */
12-6
Some escape sequences of characters
\a 0x07 BEL
\b 0x08 BS
\f 0x0C FF
\n 0x0A LF
\r 0x0D CR
\t 0x09 HT
\v 0x0B VT
\\ 0x5C \
\' 0x2C '
\" 0x22 "
\? 0x3F ?
\ddd ddd Base-8 ASCII code
\xHH 0 x HH Base-16 ASCII code

12-7
Scope: Global and Local
Where is the variable accessible?
Global: accessed anywhere in program
Local: only accessible in a particular region

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 variable is declared outside all blocks

12-8
Example
#include <stdio.h>
int 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
12-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.

12-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:
counter >= STOP
x + sqrt(y)
x & z + 3 || 9 - w-- % 6

12-11
Statement
Expresses a complete unit of work
• executed in sequential order

Simple statement ends with semicolon


z = x * y; /* assign product to z */
y = y + 1; /* after multiplication */
; /* null statement */

Compound statement groups simple statements


using braces.
• syntactically equivalent to a simple statement
{ z = x * y; y = y + 1; }
12-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

12-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.

12-14
Assignment Operator
All expressions evaluate to a value,
even ones with the assignment operator.

For assignment, the result is the value assigned.


• usually (but not always) the value of the right-hand 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.

12-15
Arithmetic Operators
Symbol Operation Usage Precedence Assoc
* multiply x * y 6 l-to-r
/ divide x / y 6 l-to-r
% modulo x % y 6 l-to-r
+ addition x + y 7 l-to-r
- subtraction x - y 7 l-to-r

All associate left to right.


* / % have higher precedence than + -.

12-16
Arithmetic Expressions
If mixed types, smaller type is "promoted" to larger.
x + 4.3
if x is int, 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.

12-17
Bitwise Operators
Symbol Operation Usage Precedence Assoc
~ bitwise NOT ~x 4 r-to-l
<< left shift x << y 8 l-to-r
>> right shift x >> y 8 l-to-r
& bitwise AND x & y 11 l-to-r
^ bitwise XOR x ^ y 12 l-to-r
| bitwise OR x | y 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.

12-18
Logical Operators
Symbol Operation Usage Precedence Assoc
! logical NOT !x 4 r-to-l
&& logical AND x && y 14 l-to-r
|| logical OR x || y 15 l-to-r

Treats entire variable (or value)


as TRUE (non-zero) or FALSE (zero).

Result is 1 (TRUE) or 0 (FALSE).

12-19
Examples
1. if ( !a)
// a = 0

2. if (a % 2 == 0)
-> if ( ! (a % 2 ) )

3. if (c >= ‘a’ && c <= ‘z’ || c >= ‘A’ && c <= ‘Z’)
// ?

12-20
Example
Input a character, check if it is a letter or not

int c;

c = getchar ();

if (c >= ‘a’ && c <= ‘z’ || c >= ‘A’ && c <= ‘Z’)
printf (“%c is a letter”, c);

12-21
How about this,
Input a character, check if it is NOT a letter

int c;

c = getchar ();

if (? )
printf (“%c is NOT a letter”, c);

12-22
Relational Operators
Symbol Operation Usage Precedence Assoc
> greater than x > y 9 l-to-r
>= greater than or equal x >= y 9 l-to-r
< less than x < y 9 l-to-r
<= less than or equal x <= y 9 l-to-r
== equal x == y 10 l-to-r
!= not equal x != y 10 l-to-r

Result is 1 (TRUE) or 0 (FALSE).

Note: Don't confuse equality (==) with assignment (=).

12-23
Special Operators: ++ and --
Changes value of variable before (or after)
its value is used in an expression.

Symbol Operation Usage Precedence Assoc


++ postincrement x++ 2 r-to-l
-- postdecrement x-- 2 r-to-l
++ preincrement ++x 3 r-to-l
-- predecrement --x 3 r-to-l

Pre: Increment/decrement variable before using its value.


Post: Increment/decrement variable after using its value.

12-24
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)

12-25
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 reader 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.
12-26
Variables and Memory Locations
In our examples,
a variable is always stored in memory.

When assigning to a variable,


must store to memory location.

A real compiler would perform code optimizations


that try to keep variables allocated in registers.
Why?

12-27
Example:
#include <stdio.h>
int inGlobal;

main()
{
int inLocal; /* local to main */
int outLocalA;
int outLocalB;

/* initialize */
inLocal = 5;
inGlobal = 3;

/* perform calculations */
outLocalA = inLocal++ & ~inGlobal;
outLocalB = (inLocal + inGlobal) - (inLocal - inGlobal);

/* print results */
printf("The results are: outLocalA = %d, outLocalB = %d\n",
outLocalA, outLocalB);
}
12-28
Special Operator: Conditional
Symbol Operation Usage Precedence Assoc
?: conditional x?y:z 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 z

1 0
x

12-29
Example

If statement:
if (a ==5)
b = 2;
else
b = 4;

Conditional expresion:
b = (a == 5) ? 2 : 4;

12-30
Comma operator

(value 1) , (value 2)

Example:
1. a = 2;
b = (2 , a + 1);

2. for (i =1, s = 0; i < n; i++)


...

12-31
Homework

12.1 -> 12.20

12-32

You might also like