C programming
Introduction to the C
programming language
Gabriele Cecchetti
October 2020
“The textbook” about C
Kernighan and Ritchie: The C Programming Language
G. Cecchetti C programming 2
What is C?
Invented by Dennis Ritchie - AT&T Bell Labs, in
1972
Widely used today
Extends to newer system architectures
Efficiency/performance
Low-level access
G. Cecchetti C programming 3
C Evolution
1972 - C Invention
1978 - 1st specification published (K&R C)
1989 - C89 standard (ANSI C or standard C)
1990 - ANSI C adopted by ISO, AKA C90
1999 - C99 standard
Not completely implemented in many compilers
2011 – C11 standard
2018 – C18 standard
(maybe 2021+ – C2x will be the next standard)
G. Cecchetti C programming 4
C Features
Few keywords
Structures, unions, compound data types
Pointers, arrays
Standard library
Compiles to native code
Macro preprocessor
G. Cecchetti C programming 5
C usage
Systems programming
Operating systems
Microcontrollers
Embedded processors
DSP processors
Network devices (switches, routers, etc)
G. Cecchetti C programming 6
C vs. Others languages
Recent derivatives: C++, C#, Objective-C
Had some influence on: Java, Perl, PHP, Python
C lacks:
Exceptions
Range checking
Garbage collection
OOP
…
C is a lower level language
It can interact/exploit directly HW
components/features
G. Cecchetti C programming 7
C source and header files
*.c extension for C source files
*.h extension for C header files
They are editable by any text editor, or
you can use any suitable IDE (Integrated
Development Environment) like:
Eclipse CDT, MS VC++ Express edition, VS code,…
These IDE suitable for large programs and they
include Editor, Compiler, Debugger, …
G. Cecchetti C programming 8
Basic C program
First steps
G. Cecchetti C programming 9
My first C program
Let’s start with a classic: hello.c
#include <stdio.h>
int main()
{
printf("Hello world!\n");
return 0;
}
#include includes definitions for library functions (in this
case, the printf() function is defined in header
file stdio.h)
main this function must always be present in a C
program. It is the first function to be invoked (the
entry point)
return end of the function, returns a value to the shell
G. Cecchetti C programming 10
How to compile and run the program
The C language is a compiled language
It means that the above program must be translated into
a binary code before being executed
The compiler does the job
reads the source file, translates it into binary code,
and produces an executable file
In FreeBSD, Linux and other Unix systems, the
following to compile and then run the program use
the following commands:
> gcc hello.c -o hello
>./hello
Hello world!
G. Cecchetti C programming 11
Compiling the code
The translation from high-level language to binary
is done by the compiler (and the linker)
the compiler translates the code you wrote in the source
file (hello.c)
the linker links external code from libraries of existing
functions (in our case, the printf() function for output
on screen) gcc hello.c −o hello hello
G. Cecchetti C programming 12
Multiple source files
A program can consist of multiple source files
Every source file (.c) is called module and usually
consists of a set of well-defined functions that work
together
Every source file is compiled separately (it is a
compilation unit) to produce an object file
(extension: .o or .obj)
All objects files and libraries are then linked
together to produce an executable
We will see later how it works
G. Cecchetti C programming 13
Running a program
To execute a program, you must tell the Operating
System to:
load the program in main memory (RAM)
start executing the program instructions sequentially
The OS is itself a program!
It is a high-order program that controls the execution of
user programs
The OS can:
execute several user programs concurrently or in parallel
suspend or kill a user program
coordinate and synchronize user programs
let them communicate and exchange data
and many other things!
G. Cecchetti C programming 14
C language syntax and fundamentals
Declaration, definitions and the
main function
G. Cecchetti C programming 15
Declarations and definitions
A C program is a sequence of global declarations
and definitions
declarations of global variables and functions
definitions of variables and functions
often, declarations are implicit (the definition is an implicit
declaration)
int a; // declaration + definition
int b = 10; // declaration + definition + initialization
int f(int); // declaration only
int f(int p) // definition
{
...
}
int g() // declaration + definition
{
...
}
G. Cecchetti C programming 16
Functions
The code goes inside functions
There must be always at least one definition of a
function called main
In the hello.c example:
#include <stdio.h>
int main()
{
printf("Hello world!\n");
return 0;
}
G. Cecchetti C programming 17
The main() function
When a program is launched, the OS implicitly
calls the main function
The main function is also called the program entry
point.
Its minimal form is:
int main(void);
If programs takes arguments, its form is:
int main(int argc, char *argv[]);
G. Cecchetti C programming 18
Anatomy of the main function
Then general form of main function is:
int main(int argc, char *argv[])
{
...
}
main is the function name, and must be unique in a
program;
int is the return type (will see later);
between () parenthesis we have the list of parameters with
their type, separated by commas:
in the example above, two parameters, argc and argv;
between {} parenthesis, we have the function body:
the code that is executed when the function is called.
G. Cecchetti C programming 19
C language syntax and fundamentals
Data types, variables and
constants
G. Cecchetti C programming 20
Data types
A type dictates the variable range (or domain) (from
the number of bits) and the operations you can
perform on an variable
In C, every variable must have a type
C has a small family of predefined datatypes
numeric:
int an integer number (usually 32 bits)
float a floating-point number, single precision (32 bits)
double a floating-point number, double precision (64 bits)
character:
char an ASCII character (8 bits)
user defined:
struct, union
G. Cecchetti C programming 21
Signed and unsigned data types
A numeric data type can be signed or unsigned:
G. Cecchetti C programming 22
Constants
Constants are numeric, alphabetic or literal fixed
values that can be used in operations on variables,
expressions or in functions; e.g.
integers
const int a = 3;
const int b = 3UL;
const int c = 0x12;
floating point
const float pi = 3.141;
character and literals
const char d = 'A';
const char e = '\x41';
const char newline = '\n'
string
const char* s = "Hello world";
G. Cecchetti C programming 23
The enum data type
enum is the abbreviation for ENUMERATE, and we can use
this keyword to declare and initialize a sequence of integer
constants.
enum colors {RED, YELLOW, GREEN, BLUE};
If you don't assign a value to a constant, the default value
for the first one in the list - RED in our case, has the value of
0. The rest of the undefined constants have a value 1 more
than the one before, so in our case, YELLOW is 1, GREEN is
2 and BLUE is 3.
But you could assign values if you wanted to:
enum colors {RED=1, YELLOW, GREEN=6, BLUE };
In this case YELLOW is 2 and BLUE is 7.
G. Cecchetti C programming 24
Variables
A variable is a location in memory with a symbolic
name
A variable is used as temporary or permanent storage
of data to perform complex computation
Therefore a variable is named link/reference to the value
stored in the system's memory or an expression that can
be evaluated
In C, every variable must have a type
G. Cecchetti C programming 25
Declaring variables
Must declare variables before use
The general form of variable declaration is:
type variable_name [ = initial_value][,][ ... ];
Can declare/initialize multiple variables at once
Usually, declaration and definition coincide for variables
The definition consists of the type keyword followed by the name of the
variable, followed by the “;” symbol.
Examples:
int a; /* an integer variable of name a */
double b; /* a double-precision floating point */
char c; /* a character */
...
a = 10; /* assignment: a now contains 10 */
b = b + 1.5; /* after assignment, b is equal to the previous
value of b plus 1.5 */
c = 'a'; /* c is equal to the ASCII value
of character 'a' */
G. Cecchetti C programming
26
Variable names
cannot start with a number
cannot contain spaces
cannot contain special symbols like ‘+’, ‘-’, ‘*’, ‘/’,
‘%’, etc.
cannot be arbitrarily long (255 char max)
cannot be equal to reserved keywords (like int,
double, for, etc.)
G. Cecchetti C programming 27
Variable initialization
It is possible to assign an initial value to a variable
during definition.
If you do not specify a value, the initial value of the
variable is default (if it is static or global) or
undefined (if it is automatic) [we will see this later].
It is good programming practice to always initialize
a variable.
Many programming errors are due to programmers that
forget to initialize a variable before using it:
int a = 0; /* the initial value of a is 0 */
int i; /* undefined initial value of i*/
int b = 4; /* the initial value of b is 4 */
b = i + 5; /* error! the value of i is not defined! */
G. Cecchetti C programming 28
Operations on variables
The basic arithmetic operators are:
+ addition,
- subtraction,
* multiplication,
/ division,
% modulus (remainder of the integer division).
Notes:
when division is applied to integers, the result is an integer (it
truncates the decimal part);
modulus can only be applied to integers;
multiplication, division and modulus have precedence over addition
and subtraction;
to change precedence, you can use parenthesis.
G. Cecchetti C programming 29
Expression
A C program is a sequence of expressions, and expression
is a combination of operators on variables, constants and
functions. Example:
/* definitions of variables */
int a, b;
int division;
int remainder;
double area_circle;
double radius;
/* expressions */
a = 15;
b = 6;
division = a / b;
remainder = a % b;
radius = 2.4;
area_circle = 3.14 * radius * radius;
G. Cecchetti C programming 30
Assignment and expressions
Assigning a value to a variable is itself an
expression:
area_circle = 3.14 * radius * radius;
The above expression is composed by three
elements:
the operator is =
the left operand must always be a variable name (cannot
be another expression!);
the right operand can be any expression, (in our case two
multiplications);
the right operand is evaluated first, and then the result is
assigned to the left operand (the variable).
G. Cecchetti C programming 31
Assignment expressions
The following expression is perfectly legal:
int a, b;
b = a = 5;
You must read it from right to left:
a = 5 is first evaluated by assigning value 5 to variable a;
the result of this expression is 5
then, the result is assigned to variable b (whose value after
assignment is hence 5)
What are the values of a and b after the following two
expressions?
int a, b;
b = (a = 5) + 1;
b = a = 5 + 1;
G. Cecchetti C programming 32
Variables
Simple I/O
G. Cecchetti C programming 33
Formatted output
To output on screen, you can use the printf
library function (example exprintf.c)
#include <stdio.h>
int main()
{
printf("Characters: %c %c \n", ’a’, 65);
printf("Decimals: %d %ld\n", 1977, 650000);
printf("Preceding with blanks: %10d \n", 1977);
printf("Preceding with zeros: %010d \n", 1977);
printf("Some different radixes: %d %x %o %#x %#o \n",
100, 100, 100, 100, 100);
printf("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416,
3.1416);
printf("Width trick: %*d \n", 5, 10);
printf("%s \n", "A string");
return 0;
}
G. Cecchetti C programming 34
Formatted output: printf
int printf(char format[], arg1, arg2, ... )
It takes in a variable number of arguments.
It returns the number of characters printed.
The format can contain literal strings as well as
format specifiers (starts with %).
printf("hello world\n");
printf("%d\n", 10);
printf("Prices: %d and %d\n", 10,20);
G. Cecchetti C programming 35
printf format specification - type
%[flags][width][.precision][length]<type>
G. Cecchetti C programming 36
printf format specification - width
%[flags][width][.precision][length]<type>
G. Cecchetti C programming 37
printf format specification - flag
%[flags][width][.precision][length]<type>
G. Cecchetti C programming 38
printf format specification - precision
%[flags][width][.precision][length]<type>
G. Cecchetti C programming 39
printf format specification - modifier
%[flags][width][.precision][length]<type>
G. Cecchetti C programming 40
Formatted input
To input variables from the keyboard, you can use
the scanf library function
#include <stdio.h>
int main ()
{
char str[80];
int i;
printf("Enter your family name: ");
scanf ("%s",str);
printf("Enter your age: ");
scanf ("%d",&i);
printf("Mr. %s , %d years old.\n", str, i);
printf("Enter a hexadecimal number: ");
scanf ("%x",&i);
printf("You have entered %#x (%d).\n", i, i);
return 0;
}
G. Cecchetti C programming 41
Formatted Input: scanf
int scanf(char* format, ... )
scanf reads characters from standard input, interpreting
them according to format specification.
Similar to printf , scanf also takes variable number of
arguments.
Arguments must be address of variables.
The format specification is the same as that for printf .
When multiple items are to be read, each item is assumed
to be separated by white space.
scanf ignores white spaces.
It returns the number of items read or EOF.
G. Cecchetti C programming 42
Exercises
See exscanf.c example
1) Write a program that asks the user to enter the
radius of a circle, computes the area and the
circumference
define variables and initialize them
use scanf to input radius variable
compute the values
formatted input on screen
2) Write a program that asks for two integer numbers
a and b, computes the quotient and the remainder,
and prints them on screen
G. Cecchetti C programming 43