You are on page 1of 47

INTRODUCTION TO

THE C PROGRAMMING LANGUAGE


What is C?

C is a general-purpose programming language.


It provides all fundamental control-flows (grouping,
decision making, looping) to create any programs.
It provides macro/pre-processing mechanism.
Strong type-checking. Compiler will give out
warnings or stop if it detects errors in the code.
C is relatively low level. It lets you mess with
memory directly, and access data to the 'bit'
What's C? (Cont.)
Unlike Java, C doesn't have class & members.
Don't expect to call string.length()
All C compilers provide common standard library
(ANSI-C 1988).
It doesn't provide protection mechanisms such as
exception or garbage collector. Programmer has to
totally take care of everything himself.
C programming is an art.
1. Types, Operators, Expressions
Variables & constants are basic objects
Declarations: name the variables to be used, and
additionally their initial values
Operators: specify what to do to var's & constants
Expressions: combine variables, constants &
operators to produce new values
Types: object belongs to a specific type, which
determines what range of values it can have, which
operations can be performed on it.
1.1. Variable Names
Names are made up of letters & digits & _
Case-sensitive (x and X are not the same)
C language-specific keywords such as if, else, for, int,
etc. are reserved.
It's advisable to give variables descriptive names, plus
prefix/suffix to indicate type and/or scope.
E.g, strABC is a string; iXYZ is an integer; g_iXYZ is
a integer global variable; a_iXYZ is a function
argument and so on
1.2. Data types
Same as Java
For integer, have signed & unsigned
Type Description Size

char Capable of holding one character in 1-byte


ASCII table (hence the name)
short int 16-bit integer 2-byte

int/long/ 32-bit integer 4-byte


long int
long long 64-bit integer 8-byte
float Single-precision floating point 4-byte
double Double-precision floating point 8-byte
1.3. Constants
Numeric constant
signed unsigned
int 1234 1234U(u)
long long 123456789L 123456789UL(ul)
float 1.234F(f)
double 1.234

Character constant: is an integer written as one


character within single quote, such as 'x', and can be
used like any other integers.
Special characters:
Constants (cont.)
Constant expression: containing only constants, and it
is evaluated at compile-time
String constant: a sequence of zero or more
characters, surrounded in double quotes
I am your friend
Internally, each string requires an additional null
character '\0' at the end. 1234 requires actual storage
of 5 bytes in memory.
Remember: 'x' is a character, x is a string containing
1 character
Constants (cont.)
Enumeration constant:
- An enumeration is a list of constant integers
enum Color { BLACK, WHITE, YELLOW };

- BLACK = 0, WHITE = 1 & so on


- or, we can specify values directly
enum Color { BLACK = 1, WHITE = 3, YELLOW = 5 };

Can achieve the same purpose with #define


1.4. Declarations
Examples:

Initialization

Using const: the value of variable will not be changed


1.5. Operators
Arithmetic operators: + - * / %
Relational operators: > >= < <= == !=
Logical operators: && || ! (unary negation)
Increment/Decrement operators: ++ --
Note: n++ is not the same as ++n
Bitwise operators:
2. Control Flow
Statements & blocks
If-else
Switch-case
For
While
Do-while
Break & continue
2.1. if-else
Simplest case:

Multi-way decision:
expressions are
evaluated in order
2.2. switch-case
Multi-way decision to test whether an expression
matches one of a set of constant values

Example:
(note break)
2.3. for & while
Usage:

The for loop can be rewritten as

Infinite loop: for(;;) or while(1)


Note that, if the test on expr2 fails, the inner
statements will never run even once.
2.4. do-while
Usage:

The inner-loop statements will run at least once.


2.5. break & continue
break provides an early exit from for, while or switch. It causes the
innermost enclosing loop or switch to be exited immediately

continue causes the next iteration of enclosing for, while to begin


3. Functions & Program Structure
Functions break large task into smaller ones
Functions help hiding parts of code from other parts
which don't need to know about them readability &
source code organization
Functions allow reusability
C is essentially a functional language. A C program
may consist of many small functions, scattered in
different source files that are compiled and linked
together.
3.1. Basics of functions
Function (my definition) is a part of code that perform
some specific task(s).
Function passes input arguments by values
Function may return values to some output
arguments, via pointers if used
Function may or may not return a value to the caller,
via the return statement.
In general, a function has the following form:
Example
Function to read a string into a double
3.2. Scope
The scope of a name is the part of the program within
which the name can be used.
For an automatic variable declared inside a function,
its scope is in that function, thus called local variable.
Local variables of the same name in different functions
are unrelated. The same holds the function parameters,
which are actually local variables.
For a global variable (defined outside of any
functions), its scope is from the point where it is
declared to the end the source file.
3.3. Static variables
Declared using the static keyword.
If used for global variable or function, that
variable/function is restricted for use within the current
source file only.
A static variable inside a function exists throughout
the running-time of a program. It means the static
mechanism provides a permanent storage within that
single function.
3.4. extern keyword
extern is used to declared a reference to a variable or
function in a different source file. The variable/function
will be linked at compile-time.
Distinguish between definition & declaration: A
declaration announces properties of a variable or a
function; a definition actually allocates storage to them.
3.5. Header files
Serve to separate declarations/definitions. In general,
the header files contain declarations, whereas the
source files contain actual definition (or
implementation, to be clear).
However, there's no such restriction from the
complier. The header can contain implementation as
well
Example of C program:
3.6. Entry point
In a C program, an entry point is the main() function.
The main() function must be defined in a source file.
Can only define one main() function in one program
Typically, the main() function takes input arguments,
which are command-line parameters you specify while
executing the program.
int main(int argc, char* argv[])
4. Pointers
A pointer is a variable that contains the address of a
variable.
Pointers are used very often in high-performance
program because of direct memory access (DMA).
Example:
Pointers
The value of the variable that the pointer points to:
(*p)
Pointer increment: p++ : point to the next chunk of
memory of the same size as the current address
Pointer decrement: p-- : point to prior chunk of
memory to the current address
4.2. Pointers as function arguments
C passes arguments as values, so there's no direct way
to change values of variables passed on as arguments.
We have to use pointers
Example: swapping
Wrong Correct
4.3. Pointers and Arrays
Pointers & arrays are strongly related.
Example: define: int a[10];

Declare a ptr: int *pa = &a[0]; or just int *pa = a;

*pa refers to a[0]; *(pa+1) refers to a[1] and so on


4.4. Pointer Array
Pointers are variables, thus can be stored in array
4.5. Const pointers
const <type> *<var>
The data that <var> points to is immutable.
<var> can be changed to point to smth else.
Useful when passing data to a function, but don't want
the function to modify the data.
<type> * const <var>
<var> is immutable, but the data <var> points to can be
changed.
const <type> * const <var>
<var> cannot be changed, likewise the data <var> points
to.
C program's memory management
Static Static variables are allocated in memory,
along with executable code & persist for
the whole running time
Size must be specified at compile-time
Automatic Automatic, or local, variables are allocated
in stack. They come and go as functions are
called and return.
Size must be specified at compile-time
Dynamic Variables are allocated at run-time, on the heap
5. String
String is an array of char, terminated by a null
character ('\0', or simply 0).
Each element is an 8-bit integer. That number is
interpreted as a character by looking up the ASCII
table.
How C knows about the string, given a pointer to
the first character? It reads the array char-by-char
until it encounters the null character.
C doesn't really perform bound-check, the
programmer must be careful when handling
strings, (see example), or arrays in general.
String examples
char *str = abcd; /* const string */
str[0] = 'e'; /* segfault */
char str[] = abcd; /* mutable */
str[0] = 'e'; /* ok */
sizeof(str) == 5; strlen(str) == 4;
char str[4] = abc; /* sizeof = 4, strlen = 3 */
char str[4] = abcd; /* size? length? */
sizeof(str) == 4;
strlen(str) = ? C will count until it reaches a '0' byte
in memory
6. Dynamic memory management
#include <stdlib.h>
malloc allocates a specified number
of bytes

realloc increases or decreases the size


of the memory block. May
reallocate if needed
calloc same as malloc, plus clearing
every element to zero

free releases the memory block


Dynamic memory
Example:
int *p = malloc(10*sizeof(int)); /* 10 integers */
if(p == NULL) { /*error handling*/ }
/* do something to p */
free(p); /* done, release */
p = NULL; /* make sure p doesn't point to
anything */
Must free(p) before assigning p another value
Type safety & errors
Example:
int *p = (int*)malloc(10*sizeof(int)); /*cast*/
Help identify type consistency in the program
Common errors:
- Not checking for allocation failures
- Forget to release memory, causing 'leak'
- Accessing the memory block before mallocing
or after freeing
7. Function Pointer
Pointer, point to address of function
Example:
float Plus(float a, float b) { return a+b; }
float (*pt2Func)(float, float);
pt2Func = &Plus; /* standard */
or
pt2Func = Plus; /* short form */
Calling:
pt2Func(a, b) or (*pt2Func)(a, b)
Passing/Returning Function Pointer
For easy reading: use typedef
typedef float (*PT2FUNC)(float, float);
Passing function pointer as argument
void DoIt(PT2FUNC pt2func)
Return a function pointer
PT2FUNC GetFuncPtr() { return &Plus; }
Array of function pointers
PT2FUNC funcPtrArray1[10] = {NULL};
float (*funcPtrArray2[10])(float, float) = {NULL};
8. Struct & Union
struct TA union TA
{ {
char name[20]; char name[20];
int ID; int ID;
}; };
Struct & Union
typedef struct _TA typedef union _TA
{ {
char name[20]; char name[20];
int ID; int ID;
} TA; } TA;

sizeof(TA): 24 sizeof(TA): 20
9. C Preprocessor & macros
First processing step in compilation
C preprocessor directives:
File inclusion #include

Macro definition #define


#undef

Conditional #if; #elif; #endif

#ifndef is equivalent to #if !defined()


Using macros
Syntax: #define NAME replacement text
Replacement text can be spread in several lines
by using '\' at the end of each line
Subtitutions do not take place within quoted
string, e.g NAME
Examples:
#define FOREVER for(;;)
#define max(a, b) ((a) > (b) ? (a) : (b))
Macros
x = max(p+q, r+s);
is read as
x = ((p+q) > (r+s) ? (p+q) : (r+s));
Pitfall: x = max(p++, q++);
which is: x = ((p++) > (q++)) ? (p++) : (q++));
Remember using parentheses properly
#define square(x) x*x /*should be (x)*(x)*/
a = square(b+1) is read as a = b+1*b+1
Parameter name string
Use '#' to turn parameter name into string
#define dprint(p) printf(#p =%f\n, p)
dprint(x/y) printf(x/y =%f\n, x/y)
Use '##' to concatenate parameters into string
#define stitch(A, B) A ## B
stitch(stud, ents) students
Nested '##'? read the book please!
Any questions?

You might also like