Lec02 C Intro
Lec02 C Intro
Introduction to C
3
Favorites: binary and hexadecimal (plus decimal)
Hex is a convenient way to represent binary
Computer Science 61C Fall 2021 Wawrzynek and Weaver
5
Unsigned Integers: 32-bit example
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• Signed integers in C; want ½ numbers <0, want ½ numbers >0, and want
just a single 0
• Two’s complement treats 0 as positive, so 32-bit word represents 232
integers from
-231 (–2,147,483,648) to 231-1 (2,147,483,647)
• Note: one negative number with no positive version
• Book lists some other options:
• All of which are worse except in very limited circumstances
• Every computer uses two’s complement integers today
• Most-significant bit (leftmost) is the sign bit, since 0 means positive
(including 0), 1 means negative Sign-bit has negative weight
• Bit 31 is most significant, bit 0 is least significant
7
Two’s-Complement Integers
Computer Science 61C Fall 2021 Wawrzynek and Weaver
Sign Bit 0000 0000 0000 0000 0000 0000 0000 00002 = 010
0000 0000 0000 0000 0000 0000 0000 00012 = 1ten
0000 0000 0000 0000 0000 0000 0000 00102 = 2ten
... ...
0111 1111 1111 1111 1111 1111 1111 11012 = 2,147,483,64510
0111 1111 1111 1111 1111 1111 1111 11102 = 2,147,483,64610
0111 1111 1111 1111 1111 1111 1111 11112 = 2,147,483,64710
1000 0000 0000 0000 0000 0000 0000 00002 = –2,147,483,64810
1000 0000 0000 0000 0000 0000 0000 00012 = –2,147,483,64710
1000 0000 0000 0000 0000 0000 0000 00102 = –2,147,483,64610
... ...
1111 1111 1111 1111 1111 1111 1111 11012 = –310
1111 1111 1111 1111 1111 1111 1111 11102 = –210
1111 1111 1111 1111 1111 1111 1111 11112 = –110 8
Ways to Make Two’s Complement
Computer Science 61C Fall 2021 Wawrzynek and Weaver
Carry
0010
3 0011
+2 0010
5 0 01 0 1
10
Two’s-Complement Addition Examples
Computer Science 61C Fall 2021 Wawrzynek and Weaver
☐ 0 to +31
☐ -16 to +15
☐ -15 to +16
12
Computer Science 61C Fall 2021 Wawrzynek and Weaver
☐ 0 to +31
☐ -16 to +15
☐ -15 to +16
13
In digital systems everything stored, communicated,
and manipulated is done using bits...
Computer Science 61C Wawrzynek and Weaver
possible things
• So far we have talked about representing integers, but could represent pixel
values, sound samples, floating-point numbers, …
14
How collections of bits are treated is dependent on
the context (PL types help define the context)
Computer Science 61C Wawrzynek and Weaver
16
Agenda
Computer Science 61C Wawrzynek and Weaver
• Computer Organization
• Compile vs. Interpret
• C vs Java
• Arrays and Pointers (perhaps)
17
ENIAC (U.Penn., 1946)
First Electronic General-Purpose Computer
Computer Science 61C Wawrzynek and Weaver
19
Components of a Computer
Computer Science 61C Wawrzynek and Weaver
Memory
Processor (CPU/core) Input
Enable?
Read/Write
Control
Program
Datapath
Address
PC Bytes “Read Data” is both
Write instructions and data
Registers Data
Machine
Interpretation
Hardware Architecture Description
(e.g., block diagrams)
Architecture
Implementation
“K&R” 22
Intro to C
Computer Science 61C Wawrzynek and Weaver
23
Intro to C
Computer Science 61C Wawrzynek and Weaver
• Why C?: we can write programs that allow us to exploit underlying features of
the architecture (memory management, special instructions) and do it in a
portable way (C compilers universally available for all existing processor
architectures)
• C and derivatives (C++/Obj-C/C#) still one of the most popular application
programming languages after >40 years!
• It’s popularity is mainly because of momentum:
• Most Operating Systems (Linux, Windows) written in C (or C++),
• as are world’s most popular databases, including Oracle Database, MySQL, MS SQL Server, and PostgreSQL.
• However, if you are starting a new project where performance matters consider either Go or Rust
• Rust, “C-but-safe”: By the time your C is (theoretically) correct with all the necessary checks it should be no
faster than Rust.
• Go, “Concurrency”: Actually able to do practical concurrent programming to take advantage of modern multi-
core microprocessors.
24
Recommendations on using C
Computer Science 61C Wawrzynek and Weaver
• Otherwise, don't...
• If you can tolerate GC pauses, go (aka golang) is really nice
• Or C#, Java, Scala, Swift, etc...
• If you can't, there is rust...
25
Disclaimer
Computer Science 61C Wawrzynek and Weaver
• You will not learn how to fully code in C in these lectures! You’ll still need
your C reference for this course
• K&R is a must-have
• Useful Reference: “JAVA in a Nutshell,” O’Reilly
• Chapter 2, “How Java Differs from C”
• http://oreilly.com/catalog/javanut/excerpt/index.html
• Brian Harvey’s helpful transition notes
• On CS61C class website: pages 3-19
• http://inst.eecs.berkeley.edu/~cs61c/resources/HarveyNotesC1-3.pdf
• Computer Organization
• Compile vs. Interpret
• C vs Java
27
Compilation: Overview
Computer Science 61C Wawrzynek and Weaver
Compiler Compiler/assembler
Compiler
combined here
• C source files first pass through “macro preprocessor”, CPP, before compiler sees code
• CPP commands begin with “#”
#include “file.h” /* Inserts file.h into output */
#include <stdio.h> /* Looks for file in standard location */
#define M_PI (3.14159) /* Define constant */
#if/#endif /* Conditional inclusion of text */
• CPP replaces comments with a single space
• Use –save-temps option to gcc to see result of preprocessing
• Full documentation at: http://gcc.gnu.org/onlinedocs/cpp/
32
CPP Macros:
A Warning...
Computer Science 61C Wawrzynek and Weaver
33
C vs. Java
Computer Science 61C Wawrzynek and Weaver
C Java
Type of Language Function Oriented Object Oriented
Programming Unit Function Class = Abstract Data Type
gcc hello.c creates javac Hello.java creates Java virtual machine
Compilation
machine language code language bytecode
a.out loads and executes
Execution java Hello interprets bytecodes
program
#include<stdio.h> public class HelloWorld {
int main(void) { public static void main(String[] args) {
hello, world printf("Hello\n"); System.out.println("Hello");
return 0; }
} }
New allocates & initializes,
Storage Manual (malloc, free)
Automatic (garbage collection) frees
From http://www.cs.princeton.edu/introcs/faq/c2java.html 34
C vs. Java
Computer Science 61C Wawrzynek and Weaver
C Java
Comments /* … */ /* … */ or // … end of line
Constants #define, const final
Preprocessor Yes No
Variable
At beginning of a block Before you use it
declaration
Variable
naming sum_of_squares sumOfSquares
conventions
Accessing a #include <stdio.h> import java.io.File;
library
From http://www.cs.princeton.edu/introcs/faq/c2java.html 35
Typed Variables in C
Computer Science 61C Wawrzynek and Weaver
int variable1 = 2; • Must declare the type of data a variable will hold
float variable2 = 1.618;
– Types can't change
char variable3 = 'A';
36
Integers: Python vs. Java vs. C
Computer Science 61C Wawrzynek and Weaver
int number_of_people ()
{
return 3;
• You have to declare the type of data you
} plan to return from a function
• Return type can be any C variable type, and
float dollars_and_cents () is placed to the left of the function name
{ • You can also specify the return type as void
return 10.33; – Just think of this as saying that no value will be returned
} • Also necessary to declare types for values
passed into a function
int sum ( int x, int y) • As with variables, functions MUST be
{ declared before they are used
return x + y;
}
39
Structs in C
Computer Science 61C Wawrzynek and Weaver
typedef struct {
int length_in_seconds;
int year_recorded;
} Song; Dot notation: x.y = value
Song song1;
song1.length_in_seconds = 213;
song1.year_recorded = 1994;
Song song2;
song2.length_in_seconds = 248;
song2.year_recorded = 1988;
40
A First C Program: Hello World
Computer Science 61C Wawrzynek and Weaver
41
C Syntax: main
Computer Science 61C Wawrzynek and Weaver
42
A Second C Program:
Compute Table of Sines
Computer Science 61C Wawrzynek and Weaver
43
Second C Program
Sample Output
Computer Science 61C Wawrzynek and Weaver
Value of PI = 3.141593
angle Sine
0 0.000000
10 0.173648
20 0.342020
30 0.500000
40 0.642788
50 0.766044
60 0.866025
70 0.939693
80 0.984808
90 1.000000
100 0.984808
110 0.939693
120 0.866025
130 0.766044
140 0.642788
....
44
C Syntax: Variable Declarations
Computer Science 61C Wawrzynek and Weaver
46
C Syntax : Control Flow (1/2)
Computer Science 61C Wawrzynek and Weaver
• if-else
• if (expression) statement
• if (x == 0) y++;
• if (x == 0) {y++;}
• if (x == 0) {y++; j = j + y;}
• if (expression) statement1 else statement2
• There is an ambiguity in a series of if/else if/else if you don't use {}s, so use {}s to block the code
• In fact, it is a bad C habit to not always have the statement in {}s, it has resulted in some amusing errors...
• while
• while (expression) statement
• do statement while (expression);
47
C Syntax : Control Flow (2/2)
Computer Science 61C Wawrzynek and Weaver
• for
• for (initialize; check; update) statement
• switch
• switch (expression){
case const1: statements
case const2: statements
default: statements
}
• break; /* need to break out of case */
• Note: until you do a break statement things keep executing in the switch statement
• C also has goto
• But it can result in spectacularly bad code if you use it, so don’t! Makes your code hard to
understand, debug, and modify.
48
C Syntax: True or False
Computer Science 61C Wawrzynek and Weaver
51
Agenda
Computer Science 61C Wawrzynek and Weaver
• Pointers
• Arrays in C
52
Remember What We Said Earlier About
Buckets of Bits?
Computer Science 61C Wawrzynek and Weaver
• Word size is 32b for a 32b architecture, 64b for a 0x08 xxxx xxxx xxxx xxxx
64b architecture: 0x04 xxxx xxxx xxxx xxxx
A word is big enough to hold an address 0x00 xxxx xxxx xxxx xxxx
53
Address vs. Value
Computer Science 61C Wawrzynek and Weaver
54
Pointers
Computer Science 61C Wawrzynek and Weaver
Location (address)
55
Pointer Syntax
Computer Science 61C Wawrzynek and Weaver
• int *p;
• Tells compiler that variable p is address of an int
• p = &y;
• Tells compiler to assign address of y to p
• & called the “address operator” in this context
• z = *p;
• Tells compiler to assign value at address in p to z
• * called the “dereference operator” in this context
56
Creating and Using Pointers
Computer Science 61C Wawrzynek and Weaver
57
Using Pointer for Writes
Computer Science 61C Wawrzynek and Weaver
p x 3
*p = 5; p x 5
58
Pointers and Parameter Passing
Computer Science 61C Wawrzynek and Weaver
y remains equal to 3
59
Pointers and Parameter Passing
Computer Science 61C Wawrzynek and Weaver
add_one(&y);
y is now equal to 4
60
Types of Pointers
Computer Science 61C Wawrzynek and Weaver
• Pointers are used to point to any kind of data (int, char, a struct,
etc.)
• Normally a pointer only points to one type (int, char, a struct, etc.).
• void * is a type that can point to anything (generic pointer)
• Use void * sparingly to help avoid program bugs, and security issues, and other bad things!
61
More C Pointer Dangers
Computer Science 61C Wawrzynek and Weaver
typedef struct {
int x; /* dot notation */
int y; int h = p1.x;
} Point; p2.y = p1.y;
63
Pointers in C
Computer Science 61C Wawrzynek and Weaver