1-Introduction To The C Programming Language
1-Introduction To The C Programming Language
Introduction to the C
programming language
Gabriele Cecchetti
October 2020
“The textbook” about C
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;
}
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)
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
G. Cecchetti C programming 16
Functions
The code goes inside functions
#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
G. Cecchetti C programming 18
Anatomy of the main function
Then general form of main function is:
int main(int argc, char *argv[])
{
...
}
G. Cecchetti C programming 19
C language syntax and fundamentals
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};
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 */
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;
G. Cecchetti C programming 31
Assignment expressions
The following expression is perfectly legal:
int a, b;
b = a = 5;
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;
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