0% found this document useful (0 votes)
5 views

Lecture 1 - Intro to C 1

The document provides an overview of the C programming language, including its history, features, and comparison with C++. It discusses the process of writing, compiling, and running C programs, as well as memory management and debugging tools. Additionally, it highlights the significance of C in the development of various operating systems and programming languages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 1 - Intro to C 1

The document provides an overview of the C programming language, including its history, features, and comparison with C++. It discusses the process of writing, compiling, and running C programs, as well as memory management and debugging tools. Additionally, it highlights the significance of C in the development of various operating systems and programming languages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

C-CS214

ComputerArchitecture and Organization


Introduction to C Programming 1

http://lol-rofl.com/computer-cartoon/

1
References

 Many slides of this lecture are either from or adapted from:


 Lewis Girod, CENS Systems Lab,
https://courses.cs.washington.edu/courses/cse461/08au/lectures/c-tutorial.ppt

 Clark Barrett
 “Machine Architecture and Organization” lectures, University of Minnesota,
https://cse.umn.edu/
 Prof. Mohamed Zahran lectures

2
C Invention
 In early 1970s, Richie started creating the C
programming language.

 In 1978 and while working at Bell labs, Richie and


Kernighan published is “The C programming
Dennis Ritchie 1
language” book.

 This book is the origin behind the “Hello, world!”


program.

Brian Kernighan 2

1 https://spectrum.ieee.org/dennis-ritchie-1941-2011
3
2 https://www.cs.princeton.edu/~bwk/
C is everywhere!

Operating systems Other languages


Windows Python
Mac OS X Java
Linux Matlab

C - language
is the mother of them all …

Mobile kernels and much more …


Embedded systems
Stores (e.g. vending iOS
machines) Android

4
C is everywhere!
Fast
Pointers
It produces code that runs nearly
Simple Direct contact
as fast as code written in assembly
Easy to learn with memory
language

Main features of
C – language1

Dynamic memory management


Size of the data structure can be and much more …
controlled during runtime

5
1 https://www.simplilearn.com/tutorials/c-tutorial/features-of-c-language
C is everywhere!

Interesting Opinion about


C – language1

“You should learn C. Because it's the abstraction other


languages use to understand the physical machine.”

1 https://www.quora.com/Financially-speaking-which-computer-languages-can-earn-the-most-for-the-
6
programmer/answer/Carter-Page-1
C vs C++: Hello World

C C++
#include <stdio.h> #include <iostream>
using namespace std;

int main() int main()

{ {
printf("Hello World!\n"); cout<<"Hello World!“<<endl;

return 0; return 0;
} }

7
C vs C++: I/O
C C++
#include <stdio.h> #include <iostream>
using namespace std;
int main() int main()
{ {
int num1 = 5; int num1 = 5;
int num2; int num2;
char ch; char ch;
printf("Number = %d\n", num1); cout<<"Number = "<<num1<<endl;
printf("Enter a number: "); cout<<"Enter a number = ";
scanf("%d",&num2); cin>>num2;
printf("You entered %d.\n",num2); cout<<"You entered "<<num2<<"."<<endl;
printf("Enter a character: "); cout<<"Enter a character = ";
scanf(" %c",&ch); cin>>ch;
printf("You entered %c.\n",ch); cout<<"You entered "<<ch<<"."<<endl;
return 0; return 0;
} } 8
C vs C++: I/O

To print a value stored in a variable, printf should know it type, using one
of the following syntax

%d Integer values
%c Characters
%s String values
%f Float values

int x; Char name[] = “Ali Saber”;


x = 10; Printf(“name is: %s”,name);
Printf(“x = %d”,x);

9
C vs C++: I/O

10
C vs C++: I/O

11
C Syntax and Hello World!
#include inserts another file. “.h” files are called “header” files.
They contain stuff needed to interface to libraries and code in
other “.c” files.

This is a comment. The compiler ignores this.

#include <stdio.h> The main() function is always


/* The simplest C Program */ where your program starts
running.
int main(int argc, char * argv[])

{ Blocks of code are marked by


printf(“Hello World!\n”); {…}

return 0;

Return ‘0’from this function. Print out a message. ‘\n’means “new line”.
Exit 12
Comments in C

13
Using escape parameters in C

Symbol Meaning
\n New line
\t Tab
\b Back space \x is a request to display the
\x Hexadecimal next argument in hexadecimal.
\xeb would mean character eb
\\ \ in hex, or 235 in decimal.
\? ?
\’ ‘
\” “

14
Writing and Running Programs
#include <stdio.h>
/* The simplest C Program */
int main(int argc, char * argv[])
{
printf(“Hello World!\n”);
return 0;
}

 To compile a C program, we will use the gcc compiler in


Linux, which stands for “GNU Compiler Collection” 1.
To compile a Created executable To run the
program, type: file name executable, type:
Example 1 $ gcc hello.c a.out $ ./a.out

Example 2 $ gcc –o hello hello.c hello $ ./hello

Default filename 15
1 https://gcc.gnu.org/
What happens when you call “gcc”?

Preprocessor Preprocessed
Source code Compiler
Source code

Libraries Linker Object file Assembler Assembly code

Executable Loader Memory

16
1 https://people.sc.fsu.edu/~jburkardt/classes/isc_2012/c_program_compilation.pdf
Writing and Running Programs
#include <stdio.h>
/* The simplest C Program */ Main steps
int main(int argc, char * argv[])
1. Write text of program (source code) using a text editor,
{ save as text file e.g. my_program.c
printf(“Hello World!\n”);
return 0;
2. Run the compiler, assembler, and linker to convert
}
program from source to an “executable” or “binary”:

$ gcc –Wall –g –o my_program my_program.c


$ gcc -Wall –g my_program.c –o my_program
tt.c: In function `main':
tt.c:6: parse error before `x'
tt.c:5: parm types given both in parmlist and separately
tt.c:8: `x' undeclared (first use in this function)
tt.c:8: (Each undeclared identifier is reported only once
3. If compiler gives errors and warnings
tt.c:8: for each function it appears in.)
tt.c:10: warning: control reaches end of non-void function
 edit source file, fix it, and re-compile.
tt.c: At top level:
tt.c:11: parse error before `return'

4. Run it and see if it works 


$ ./my_program
my_program Hello World
$▌ 17
Writing and Running Programs
 Note 1: GCC command example & compiler options

$ gcc –Wall –g –o my_program my_program.c

Warning option Output controlling option


-Wall: Enable all name the generated
warning messages output file
(default: a.out)
Debugging option Source code file(s)
-g: keep debugging one or more C files
information
18
1 https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html
Writing and Running Programs
 Note 2: Running a program
In current directory $ ./my_program

19
Writing and Running Programs
 Note 3: If your program doesn’t work, you can use
debugging tools.

Debugging Tool Function


strace It traces all system calls made by your program. This will tell
you when you call into the OS, e.g. open(), read(), write(), etc.
ltrace It traces all standard library calls made by your program.
gdb It is a source-level debugger. With this tool you can analyze
core dumps, and step through your program line by line as it
runs.
valgrind It is an x86 virtual machine that is useful for catching memory
errors such as use of freed memory, bad pointers, etc
printf debugging It is a common way to trace a program, where you put “printf “
statements throughout your code to see what’s going on.

20
What happens when you call “gcc”?

Preprocessor Preprocessed
Source code Compiler
Source code

Libraries Linker Object file Assembler Assembly code

Executable Loader Memory

21
1 https://people.sc.fsu.edu/~jburkardt/classes/isc_2012/c_program_compilation.pdf
Preprocessing
#include <stdio.h>
/* The simplest C Program */
int main(int argc, char * argv[]) Preprocess
{
printf(“Hello World!\n”);
return 0;
}

extension typedef unsigned long long int dev_t;


extension typedef unsigned int uid_t;
extension typedef unsigned int gid_t;
extension typedef unsigned long int ino_t;
extension typedef unsigned long long int ino64_t;
extension typedef unsigned int nlink_t;
extension typedef long int off_t;
extension typedef long long int off64_t;
extern void flockfile (FILE * stream) ;
extern int ftrylockfile (FILE * stream) ;
extern void funlockfile (FILE * stream) ;
int main(int argc, char * argv[])
{
printf(“Hello World!\n”);
return 0;
}

my_program
22
Compile
Preprocessing
#include <stdio.h>
/* The simplest C Program */
int main(int argc, char * argv[])
Preprocess
{
printf(“Hello World!\n”);
return 0;
}  In Preprocessing, source code is “expanded” into a
extension
dev_t;
typedef unsigned long long int larger form that is simpler for the compiler to
extension
extension
typedef
typedef
unsigned int
unsigned int
uid_t;
gid_t;
understand.
extension typedef unsigned long int ino_t;
extension typedef unsigned long long int
ino64_t;
extension typedef unsigned int nlink_t; Any line that starts with ‘#’is a line that is interpreted
by the Preprocessor.
extension typedef long int off_t;
extension typedef long long int off64_t;
extern void flockfile (FILE * stream) ;
extern int ftrylockfile (FILE * stream) ;
extern void funlockfile (FILE * stream) ;
int main(int argc, char * argv[]) • Include files are “pasted in” (#include)
• Macros are “expanded” (#define)
{
printf(“Hello World!\n”);
return 0;
} • Comments are stripped out ( /* */ , // )
• Continued lines (i.e. very long lines ) are joined ( \ )

my_program
Compile 23
What happens when you call “gcc”?

Preprocessor Preprocessed
Source code Compiler
Source code

Libraries Linker Object file Assembler Assembly code

Executable Loader Memory

24
1 https://people.sc.fsu.edu/~jburkardt/classes/isc_2012/c_program_compilation.pdf
Compiling
#include <stdio.h>
/* The simplest C Program */
int main(int argc, char * argv[])
Preprocess
{
printf(“Hello World!\n”);
return 0;
}  The compiler then converts the resulting text into
extension
dev_t;
typedef unsigned long long int binary code the CPU can run directly.
extension typedef unsigned int uid_t;
extension typedef unsigned int gid_t;
extension
extension
typedef
typedef
unsigned long int
unsigned long long int
ino_t;
 The compilation process involves really several steps:
ino64_t;
extension typedef unsigned int nlink_t; • Compiler: high level language  assembly
• Assembler: assembly  machine code
extension typedef long int off_t;
extension typedef long long int off64_t;

• Linker: links all machine code files and needed


extern void flockfile (FILE * stream) ;
extern int ftrylockfile (FILE * stream) ;
extern void funlockfile (FILE * stream) ;
int main(int argc, char * argv[]) libraries into one executable file.
{
printf(“Hello World!\n”);

 When you type gcc, you really invoke the compiler,


return 0;
}

assembler, and linker.

my_program
Compile 25
Memory

26
What is “Memory”?

• It is like a big table of numbered slots. Addr Value


• Each slot stores a byte. 0
1
• The slot number (its index) is its Address. 2
• One byte Value can be stored in each slot. 3
4 ‘H’ (72)
• Some “logical” data values span more than 5 ‘e’ (101)
one slot, like the character string “Hello\n”
6 ‘l’ (108)

• A Type names a logical meaning to a span of 7 ‘l’ (108)


memory. Some simple types are: 8 ‘o’ (111)

char a single character (1 slot) 9 ‘\n’ (10)


10 ‘\0’ (0)
char [10] an array of 10 characters
11
int signed 4 byte integer
12
float 4 byte floating point
27
What is “Memory”?

• ASCII stands for American Standard Code Addr Value


for Information Interchange. 0
1

• ASCII is the coding scheme that maps bytes 2


to characters. 3
• It is a 7-bit character code. 4 ‘H’ (72)
5 ‘e’ (101)
6 ‘l’ (108)
A to Z 65 to 90 7 ‘l’ (108)
a to z 97 to 122 8 ‘o’ (111)
9 ‘\n’ (10)
10 ‘\0’ (0)
11
12
28
1 https://www.ascii-code.com/
What is “Memory”?

Addr Value
The first 32 values, 0 through 31, are reserved for
0
terminal control codes, such as Escape, New Line,
1
Carriage Return, and Acknowledge.
2
The values from 32 to 64 are reserved for numbers 3
and special characters, such as space, Exclamation 4 ‘H’ (72)
mark, Per cent sign, Colon, and Semicolon. 5 ‘e’ (101)
6 ‘l’ (108)
The reason the characters are encoded as 7-bit values 7 ‘l’ (108)
is because early computers handled data in bytes — 8 ‘o’ (111)
blocks of 8 bits. The extra, eighth bit was originally 9 ‘\n’ (10)
reserved for error checking. 10 ‘\0’ (0)
11
12
29
1 https://www.ascii-code.com/
Variable

30
What is a “Variable”?

A Variable names a place in memory where you Symbol Addr Value


store a Value of a certain Type. 0
1
You first Define a variable by giving it a name 2
and specifying the type, and optionally an initial 3
value
x 4 ?
y 5 ‘e’ (101)
char x; Initial value of x is undefined
char y=‘e’; 6
7
Initial value The compiler puts them 8
somewhere in memory. 9
Name
10
11
Type is single character (char)
12
31
Multi-byte Variables

• Different types consume different amounts Symbol Addr Value


of memory. 0
• Most architectures store data on “word 1
boundaries”, or even multiples of the size of
2
a primitive data type (int, char)
3
char x; x 4 ?
char y=‘e’; y 5 ‘e’ (101)
int z = 0x01020304;
6
0x means the constant is 7
written in hex z 8 4
9 3
An int consumes 4 bytes
10 2
11 1
12
32
Expressions

33
Expressions in C

 What is an “expression”?
 It is a combination of operands (variables) and operators, according
to certain precedence rules.
 It computes a single value, which is stored in a variable.

operands
variable z=x+y
operator

34
Comparison and Mathematical Operators
Types of Expressions 1
Relational operators
Arithmetic operators Logical operators
+ plus && logical and == equal to
- minus || logical or < less than
* mult ! logical not <= less than or equal
/ divide > greater than
% modulo Remainder of a division >= greater than or equal
!= not equal
Bitwise operators
Beware in division:
& bitwise and If second argument is integer, the
| bitwise or
result will be integer (rounded):
^ bitwise xor
~ bitwise not
5 / 10  0 whereas 5 / 10.0  0.5
<< shift left
>> shift right Don’t confuse & and &&
1 & 2  0 whereas 1 && 2  <true>
35
1 https://www.tutorialspoint.com/cprogramming/c_logical_operators.htm
Operator Precedence in C

In C every operator has special precedence


which is associated with it. The order in
which different types of operators in an
expression are evaluated is known
as operator precedence. The operators
which has higher precedence are executed
first and operators which has lower
precedence are executed later.
How Expressions Are Evaluated?
Expressions combine Values using Operators, according to precedence.

1+2*2 1+4 5
(1 + 2) * 2  3 * 2 6

Symbols are evaluated to their Values before being combined.

int x=1;
int y=2;
x+y*y x+2*2 x+4 1+4 5

Comparison operators are used to compare values.


In C: 0 means “false”, and any other value means “true”.
int x=4;
(x < 5)  (4 < 5)  <true>
(x < 4)  (4 < 4) 0
((x < 5) || (x < 4))  (<true> || (x < 4))  <true>

Not evaluated because


first clause was true 37
#include <stdio.h>

int main(){

//Arithmetic Expression
int a = (6 * 2) + 7 - 9;
Output
printf("The arithmetic expression returns: %d\n", a); The arithmetic expression returns: 10
//Relational Expression
int b = 10; Output
printf("The relational expression returns: %d\n", b % 2 == 0); The relational expression returns: 1
//Logical Expression
int c = (7 > 9) && ( 5 <= 9);
printf("The logical expression returns: %d\n", c);
Output
The logical expression returns: 0
//Conditional Expression
int d = (34 > 7) ? 1 : 0;
printf("The conditional expression returns: %d\n", d); Output
The conditional expression returns: 1
//Pointer Expression
int e = 20;
int *addr ; Output
addr = &e;
printf("The pointer expression returns: %p\n", addr); The pointer expression returns: 0x7ffd75e944bc
//Bitwise Expression
int f = 10;
Output
int shift = f >> 1; The bitwise expression returns: 5
printf("The bitwise expression returns: %d\n", shift);

return 0;
}
38
1 https://educative.io/answers/what-are-expressions-in-c
C Operator Precedence and Associativity Note 1
The associativity
indicates in what
order operators of
equal precedence
in an expression
are applied.

Note 2
Order of precedence When in doubt,
(highest to lowest) use parentheses.

39
1 http://www.eecs.northwestern.edu/~wkliao/op-prec.htm
Assignment Operators

x = y assign y to x x += y assign (x+y) to x


x++ post-increment x x -= y assign (x-y) to x
++x pre-increment x x *= y assign (x*y) to x
x-- post-decrement x x /= y assign (x/y) to x
--x pre-decrement x x %= y assign (x%y) to x

Note the difference between ++x and x++:

int x=5; int x=5;


int y; int y;
y = ++x; y = x++;
/* x == 6, y == 6 */ /* x == 6, y == 5 */

Don’t confuse = and ==

int x=5; int x=5;


if (x==6) /* false */ if (x=6) /* always true */
{ {
/* ... */ /* x is now 6 */
} }
/* x is still 5 */ /* ... */

40

You might also like