DDCA AppC
DDCA AppC
Computer Architecture
Sarah Harris & David Harris
Appendix C:
C Programming
C. 7 Control-Flow Statements
The overall goal of this book is to give a picture of how computers work on
Appendix C :: Topics
C. 8 More Data Types
many levels, from the transistors by which they are constructed all the way up
C. 9 Standard Libraries
to the software they run. The first five chapters of this book work up through
C. 10 Compiler and Command Line
the lower levels of abstraction, from transistors to gates to logic design.
Options
Chapters 6 through 8 jump up to architecture and work back down to micro-
C. 11 Common Mistakes
architecture to connect the hardware with the software. This Appendix on C
programming fits logically between Chapters 5 and 6, covering C program-
• C Basics
ming as the highest level of abstraction in the text. It motivates the architec-
ture material and links this book to programming experience that may
Application
Software
>”hello
world!”
• Functions
already be familiar to the reader. This material is placed in the Appendix
so that readers may easily cover or skip it depending on previous experience.
Operating
Systems
Programmers use many different languages to tell a computer what to
• Operators
do. Fundamentally, computers process instructions in machine language
consisting of 1’s and 0 ’s, as is explored in Chapter 6. But programming
Architecture
• Control Flow
in machine language is tedious and slow, leading programmers to use more
abstract languages to get their meaning across more efficiently. Table eC.1
Micro-
architecture
• Loops
lists some examples of languages at various levels of abstraction.
One of the most popular programming languages ever developed is Logic +
called C. It was created by a group including Dennis Ritchie and Brian
• Arrays & Strings
Kernighan at Bell Laboratories between 1969 and 1973 to rewrite the
UNIX operating system from its original assembly language. By many
Digital
Circuits
• Structures
measures, C (including a family of closely related languages such as C++,
C#, and Objective C) is the most widely used language in existence. Its Analog
Circuits
+
−
popularity stems from a number of factors including its:
• Memory
▶ Availability on a tremendous variety of platforms, from supercomputers Devices
down to embedded microcontrollers
• Pointers
▶ Relative ease of use, with a huge user base Physics
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
void main(void) {
int result;
result = fact(4);
}
C Basics
Comments
• Single-line comments begin with “//” and continue to the
end of the line.
x += 2; //This is a single-line comment.
int machine-dependent
1
Technically, the C99 standard defines a character as “a bit representation that fits in a
byte,” without requiring a byte to be 8 bits. However, current systems define a byte as 8 bits.
11 Digital Design & Computer Architecture Digital Building Blocks
Integer Sizes
• Integer sizes in C may vary with the machine
– int may be 16 or 32 bits
– long may be 32 or 64 bits
– Best to use sized types if size truly matters
– But their names are a bit cumbersome
• Signed: int16_t, int32_t, int64_t
• Unsigned: uint16_t, uint32_t, uint64_t
https://commons.wikimedia.org/wiki/File:ASCII-Table.svg
Functions
Functions
• A function may take some inputs and may return at most
one output
• The type of the inputs is declared in the function
declaration
• Functions pass variables by value not reference
• Curly braces {} enclose the body of the function, which may
contain zero or more statements
• The type of returned value is declared in the function
declaration
• The return statement indicates the value that the function
should return to its caller
• A function must be either declared BEFORE it is used or a
function prototype declared BEFORE it is used
////////////////////////////////
// Prototypes
////////////////////////////////
int sum3(int, int, int); // needed because sum3 is called before declared
////////////////////////////////
// main
////////////////////////////////
void main(void) {
int answer;
answer = sum3(6, 7, 8);
}
////////////////////////////////
// other functions
// prototype not needed if thsse were moved before main
////////////////////////////////
int f1(int);
int f2(int);
int f1(int n) {
return f2(n-1) + 1;
}
int f2(int n) {
return f1(n-1)*2;
}
void main(void) {
int answer;
answer = f1(5);
}
Operators
Boolean (True/False) in C
• A variable or expression is considered FALSE if its
value is 0
• A variable is considered TRUE if it has any other value
– 1, 42, and -1 are all TRUE for C
• Logical operators assign FALSE as 0 and TRUE as 1
! Boolean NOT !x
− negation y = -a;
/ division z = 9 / 3; // z = 3
22 Digital Design & Computer Architecture Digital Building Blocks
% modulo z = 5 % 2; // z = 1
(type) casts a variable to (type) x = (int)c; // cast c to an
Operators Continued
sizeof() size of a variable or type in bytes
// int and assign it to x
long int y;
x = sizeof(y); // x = 4
/ division z = 9 / 3; // z = 3
% modulo z = 5 % 2; // z = 1
Additive + addition y = a + 2;
− subtraction y = a - 2;
Relational == equals y == 2
!= not equals x != 7
^ bitwise XOR y = 2 ^ 3;
| bitwise OR y = a | b;
|| Boolean OR x || y
Operators Continued
Ternary
||
?:
Boolean OR
ternary operator
x || y
y = x ? a : b; // if x is TRUE,
// y=a, else y=b
operators. Within the same category, operators are evaluated in the order
that they appear in the program.
Unary operators, also called monadic operators, have a single operand.
Ternary operators have three operands, and all others have two. The
25 Digital
ternary Design
operator & Computer
(from Architecture
the Latin ternarius meaningDigital Building
consisting Blocks
of three)
Examples
int a = 42;
int b = 0x15; // hexadecimal; = 21 in decimal
char c = 0b00001010; // binary; = 10 in decimal
Control Flow
Control Flow Statements
if
if (expression)
statement;
if/else
if (expression)
statement1;
else
statement2;
switch/case
switch (variable) {
case (expression1): statement1; break;
case (expression2): statement2; break;
case (expression3): statement3; break;
default: statement4;
}
Loops
Loops
while
while (condition)
statement;
do/while
do {
statement;
} while (condition);
for
for (initialization; condition; loop operation)
statement;
int fact(int n) {
int result = 1;
while (n > 1) result *= n--;
return result;
}
• First do initialization (i = 1)
• Then check condition (i<=n)
• If satisfied, do body (result *= i)
• Then do loop operation (i++)
• Then repeat from checking condition
do {
dest[i] = src[i];
} while (src[i++] && i < MAXLEN);
}
void main(void) {
char name[80];
int len;
char c;
Structures
Structures
• Store a collection of related information
• General format:
struct name {
type1 element1;
type2 element2;
...
};
Memory
Memory
• Variables are stored in memory
• Each primitive data type has a size
– char 1 byte
– short at least 2 bytes
– long at least 4 bytes, 8 on some 64-bit computers
– int at least 2 bytes, 4 on most 32 & 64-bit computers
– float 4 bytes
– double 8 bytes
• Arrays & structs stored in multiple consecutive locations
char c;
double d;
point p;
rect r;
int s1 = sizeof c; // s1 = 1
int s2 = sizeof(d); // s2 = 8
int s3 = sizeof(p); // s3 = 4 + 4 = 8
int s4 = sizeof(r); // s4 = 8 + 8 + 4 = 20
Memory Memory
Pointers
Pointers
• A pointer is an address in memory
• Pointer variables are declared with * and a data type
to which the pointer points
int salary1, salary2;
int *ptr; // a pointer to an integer
• & returns address of a variable
salary1 = 98500; // suppose this is at address 100 in memory
ptr = &salary1; // ptr contains 100 (the address of salary1)
#include <stdio.h>
#include <stdio.h>
Memory
Odds & Ends
Passing Structures to Functions
Complex data structures and arrays are normally passed to C
programs by address rather than copied; it’s more efficient.
void createRect(int xl, int yl, int width, int height, int color, rect *r) {
r->ll.x = x1; r->ll.y = yl;
r->ur.x = xl + width; r->ur.y = yl + height;
r->color = color;
}
int main(void) {
rect r1;
createRect(3, 5, 10, 20, 1, &r1);
}
Dynamic
Memory
Allocation
Memory Allocation
• malloc returns a pointer to allocated memory of a
certain number of bytes.
• free frees this memory.
• These functions are declared in stdlib
mat = (double*)malloc(m*n*sizeof(double));
return mat;
}
double* newIdentityMatrix(int n) {
double *mat = newMatrix(n, n);
int i, j;
int main(void) {
double *m1, *m2;
m1 = newIdentityMatrix(3);
m2 = newMatrix(3, 3);
scaleMatrix(m1, m2, 3, 3, 10);
free(m1);
}