3. Hello World Program
The source codeThe source code
#include <stdio.h>#include <stdio.h>
int main()int main()
{{
printf("Hello Worldn");printf("Hello Worldn");
return(0);return(0);
}}
4. Hello World Program
How to compile?How to compile?
$$ gcc hello.c –o hellogcc hello.c –o hello
gccgcc compiling commandcompiling command
hello.chello.c source filesource file
hellohello compiler-generated executable filecompiler-generated executable file
Note: the default output filename is “Note: the default output filename is “a.outa.out””
5. How to executeHow to execute??
./hello./hello
““./ ” indicates the following file “hello” resides under the./ ” indicates the following file “hello” resides under the
current directory.current directory.
Hello World Program
Q: why “.” is not included in $PATHQ: why “.” is not included in $PATH
environment variable?environment variable?
6. Hello World Program
A: security consideration.A: security consideration.
CommandCommand LocationLocation CommentComment
lsls /bin/ls/bin/ls provided by theprovided by the
systemsystem
lsls current directorycurrent directory virusvirus
7. NameName DescriptionDescription Size*Size* Range*Range*
charchar Character or smallCharacter or small
integerinteger
1 byte1 byte signed: -128 to 127signed: -128 to 127
unsigned: 0 to 255unsigned: 0 to 255
short intshort int
(short)(short)
Short integerShort integer 2 bytes2 bytes signed: -32768 to 32767signed: -32768 to 32767
unsigned: 0 to 65535unsigned: 0 to 65535
intint IntegerInteger 4 bytes4 bytes signed: -2147483648 tosigned: -2147483648 to
21474836472147483647
unsigned: 0 to 4294967295unsigned: 0 to 4294967295
long intlong int
(long)(long)
Long integerLong integer 4 bytes4 bytes signed: -2147483648 tosigned: -2147483648 to
21474836472147483647
unsigned: 0 to 4294967295unsigned: 0 to 4294967295
floatfloat Floating pointFloating point
numbernumber
4 bytes4 bytes 3.4e +/- 38 (7 digits)3.4e +/- 38 (7 digits)
doubledouble Double precisionDouble precision
floating point numberfloating point number
8 bytes8 bytes 1.7e +/- 308 (15 digits)1.7e +/- 308 (15 digits)
longlong
doubledouble
Long doubleLong double
precision floatingprecision floating
point numberpoint number
8 bytes8 bytes 1.7e +/- 308 (15 digits)1.7e +/- 308 (15 digits)
Data types
8. Variable DeclarationVariable Declaration
intint length = 100;length = 100;
charchar num = ‘9’; //The actual value is 57num = ‘9’; //The actual value is 57
floatfloat deposit = 240.5;deposit = 240.5;
unsigned shortunsigned short ID = 0x5544;ID = 0x5544;
Try the following statements, and see what happensTry the following statements, and see what happens
unsigned charunsigned char value = -1;value = -1;
printf(“The value is %d n”, value);printf(“The value is %d n”, value);
unsignedunsigned charchar value = 300;value = 300;
printf(“The value is %d n”, value);printf(“The value is %d n”, value);
9. Result
DefinitionDefinition Memory layoutMemory layout DisplayDisplay commentcomment
unsigned charunsigned char
value = -1value = -1
1111111111111111 255255
unsigned charunsigned char
value = 300value = 300
0010110000101100 4444 overflowoverflow
10. Local variableLocal variable
Local variables are declared within the body of a function, and canLocal variables are declared within the body of a function, and can
only be used within that function.only be used within that function.
Static variableStatic variable
Another class of local variable is the static type. It is specified by theAnother class of local variable is the static type. It is specified by the
keywordkeyword staticstatic in the variable declaration.in the variable declaration.
The most striking difference from a non-static local variable is, a staticThe most striking difference from a non-static local variable is, a static
variable is not destroyed on exit from the function.variable is not destroyed on exit from the function.
Global variableGlobal variable
A global variable declaration looks normal, but is located outside anyA global variable declaration looks normal, but is located outside any
of the program's functions. So it is accessible to all functions.of the program's functions. So it is accessible to all functions.
Variable types
11. An exampleAn example
int global = 10;int global = 10; //global variable//global variable
int func (int x)int func (int x)
{{
static int stat_var;static int stat_var; //static local variable//static local variable
int temp;int temp; //(normal) local variable//(normal) local variable
int name[50];int name[50]; //(normal) local variable//(normal) local variable
…………
}}
12. Variable Definition vs Declaration
DefinitionDefinition Tell the compiler about the variable: its typeTell the compiler about the variable: its type
and name, as well as allocated a memory cell forand name, as well as allocated a memory cell for
the variablethe variable
DeclarationDeclaration DDescribe information ``about'' the variableescribe information ``about'' the variable,,
doesn’tdoesn’t allocate memory cell for the variableallocate memory cell for the variable
14. printf()
The printf() function can be instructed to printThe printf() function can be instructed to print
integers, floats and string properly.integers, floats and string properly.
The general syntax isThe general syntax is
printfprintf( “format”, variables);( “format”, variables);
An exampleAn example
intint stud_id = 5200;stud_id = 5200;
char * name = “Mike”;char * name = “Mike”;
printfprintf(“(“%s%s ‘s ID is‘s ID is %d%d n”, name, stud_id);n”, name, stud_id);
15. Format IdentifiersFormat Identifiers
%d%d decimal integersdecimal integers
%x%x hex integerhex integer
%c%c charactercharacter
%f%f float and double numberfloat and double number
%s%s stringstring
%p%p pointerpointer
How to specify display space for a variableHow to specify display space for a variable??
printf(“The student id is %printf(“The student id is %55d n”, stud_id);d n”, stud_id);
The value of stud_id will occupyThe value of stud_id will occupy 55 characters space in thecharacters space in the
print-out.print-out.
16. Why “n”Why “n”
It introduces a new line on the terminal screen.It introduces a new line on the terminal screen.
aa alert (bell) characteralert (bell) character backslashbackslash
bb backspacebackspace ?? question markquestion mark
ff formfeedformfeed ’’ single quotesingle quote
nn newlinenewline ”” double quotedouble quote
rr carriage returncarriage return 000000 octal numberoctal number
tt horizontal tabhorizontal tab xhhxhh hexadecimalhexadecimal
numbernumber
vv vertical tabvertical tab
escape sequence
20. Example
Arithmetic operatorsArithmetic operators
int i = 10;int i = 10;
int j = 15;int j = 15;
int add = i + j;int add = i + j; //25//25
int diff = j – i;int diff = j – i; //5//5
int product = i * j;int product = i * j; // 150// 150
int quotient = j / i;int quotient = j / i; // 1// 1
iint residual = j %nt residual = j % i; // 5i; // 5
i++;i++; //Increase by 1//Increase by 1
i--;i--; //Decrease by 1//Decrease by 1
21. Comparing themComparing them
int i = 10;int i = 10;
int j = 15;int j = 15;
float k = 15.0;float k = 15.0;
j / i = ?j / i = ?
j % i = ?j % i = ?
k / i = ?k / i = ?
k % i = ?k % i = ?
22. The AnswerThe Answer
j /j / ii = 1;= 1;
j % i = 5;j % i = 5;
k / ik / i = 1.5;= 1.5;
k % i It isk % i It is illegalillegal..
Note: For %, the operands can only be integers.Note: For %, the operands can only be integers.
23. Logical Operations
What is “true” and “false” in CWhat is “true” and “false” in C
In C, there is no specific data type to represent “true” and “false”. CIn C, there is no specific data type to represent “true” and “false”. C
uses value “0” to represent “false”, and uses non-zero value to standuses value “0” to represent “false”, and uses non-zero value to stand
for “true”.for “true”.
Logical OperatorsLogical Operators
A && BA && B =>=> A and BA and B
A || BA || B =>=> A or BA or B
A == BA == B =>=> Is A equal to B?Is A equal to B?
A != BA != B => Is A not equal to B?=> Is A not equal to B?
24. A > BA > B =>=> Is A greater than B?Is A greater than B?
A >= BA >= B => Is A greater than or equal to B?=> Is A greater than or equal to B?
A < BA < B =>=> Is A less than B?Is A less than B?
A <= BA <= B => Is A less than or equal to B?=> Is A less than or equal to B?
Don’t be confusedDon’t be confused
&& and || have different meanings from & and |.&& and || have different meanings from & and |.
& and | are& and | are bitwisebitwise operators.operators.
25. Short circuiting
SShort circuiting means that we don'thort circuiting means that we don't
evaluate the second part of an AND or ORevaluate the second part of an AND or OR
unless we really need tounless we really need to..
Some practicesSome practices
Please compute the value of the followingPlease compute the value of the following
logical expressions?logical expressions?
26. int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) =>if( i < j && j < k) =>
if( i != j || k < j) =>if( i != j || k < j) =>
if( j<= k || i > k) =>if( j<= k || i > k) =>
if( j == k && m) =>if( j == k && m) =>
if(i)if(i) =>=>
if(m || j && i )if(m || j && i ) =>=>
27. int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) =>if( i < j && j < k) => falsefalse
if( i != j || k < j) =>if( i != j || k < j) => truetrue
if( j<= k || i > k) =>if( j<= k || i > k) => truetrue
if( j == k && m) =>if( j == k && m) => falsefalse
if(i)if(i) =>=> truetrue
if(m || j && i )if(m || j && i ) =>=> truetrue
Did you get the correct answers?Did you get the correct answers?
32. Loops
for statementfor statement
for (for (expression1expression1;; expression2expression2;; expression3expression3)){{
statement…statement…
}}
expression1expression1 initializes;initializes;
expression2expression2 is the terminate test;is the terminate test;
expression3expression3 is the modifieris the modifier;;
33. An exampleAn example
int x;int x;
for (x=0; x<3; x++)for (x=0; x<3; x++)
{{
printf("x=%dprintf("x=%dn",x);n",x);
}}
First time:First time: x = 0;x = 0;
Second time:Second time: x = 1;x = 1;
Third time:Third time: x = 2;x = 2;
Fourth time:Fourth time: x = 3; (donx = 3; (don’’t execute the body)t execute the body)
34. The while statementThe while statement
while (while (expressionexpression) {) {
statementstatement ……
}}
while loop exits only when the expression is false.while loop exits only when the expression is false.
An exampleAn example
int x = 3;int x = 3;
while (x>0) {while (x>0) {
printf("x=%d n",x);printf("x=%d n",x);
x--;x--;
}}
35. for <==> while
for (for (expression1expression1;;
expression2expression2;;
expression3expression3)){{
statement…statement…
}}
expression1;expression1;
while (expression2)while (expression2)
{{
statementstatement……;;
expression3;expression3;
}}
equals
36. Arrays & Strings
ArraysArrays
int ids[50];int ids[50];
char name[100];char name[100];
int table_of_num[30][40];int table_of_num[30][40];
Accessing an arrayAccessing an array
ids[0] = 40;ids[0] = 40;
i = ids[1] + j;i = ids[1] + j;
table_of_num[3][4] = 100;table_of_num[3][4] = 100;
Note: In C Array subscripts start atNote: In C Array subscripts start at 00 and end one less thanand end one less than
the array size.the array size. [0 .. n-1][0 .. n-1]
37. StringsStrings
Strings are defined as arrays of characters.Strings are defined as arrays of characters.
The only difference from a character array is, a symbol “0”The only difference from a character array is, a symbol “0”
is used to indicate the end of a string.is used to indicate the end of a string.
For example, suppose we have a character array, charFor example, suppose we have a character array, char
name[8], and we store into it a string “Dave”.name[8], and we store into it a string “Dave”.
Note: the length of this string 4, but it occupies 5 bytes.Note: the length of this string 4, but it occupies 5 bytes.
DD aa vv ee 00
38. Functions
Functions are easy to use; they allow complicated programs to be brokenFunctions are easy to use; they allow complicated programs to be broken
into small blocks, each of which is easier to write, read, and maintain.into small blocks, each of which is easier to write, read, and maintain.
This is calledThis is called modulationmodulation..
HowHow doesdoes a function look likea function look like??
returntypereturntype function_name(function_name(parameters…parameters…) )
{ {
locallocal variables declaration;variables declaration;
functionfunction code;code;
return result; return result;
}}
39. Sample functionSample function
int addition(int x, int y)int addition(int x, int y)
{{
int add;int add;
add = x + y;add = x + y;
return add;return add;
}}
How toHow to call a function?call a function?
int result;int result;
int i = 5, j = 6;int i = 5, j = 6;
result = addition(i, j);result = addition(i, j);
40. Pointers
Pointer is the most beautifulPointer is the most beautiful ((ugliestugliest)) part of C, but alsopart of C, but also
brings most trouble to C programmers. Over 90% bugs inbrings most trouble to C programmers. Over 90% bugs in
the C programs cthe C programs coome from pointers.me from pointers.
““The International Obfuscated C Code ContestThe International Obfuscated C Code Contest ””
((http://www.ioccc.org/http://www.ioccc.org/))
What is a pointerWhat is a pointer??
A pointer is a variable which contains the address in memoryA pointer is a variable which contains the address in memory
of another variable.of another variable.
In C we have a specific type for pointers.In C we have a specific type for pointers.
41. Declaring a pointer variableDeclaring a pointer variable
int * pointer;int * pointer;
char * name;char * name;
How to obtain theHow to obtain the addressaddress of a variableof a variable??
int x = 0x2233;int x = 0x2233;
pointer = &x;pointer = &x;
where & is calledwhere & is called address ofaddress of operator.operator.
How to get theHow to get the valuevalue of the variable indicated by theof the variable indicated by the
pointerpointer??
int y = *pointer;int y = *pointer;
42. 3333 2222 0000 0000
0x5200 0x5203
0x5200
pointer
What happens in the memory?
Suppose the address of variable x is 0x5200 in the above
example, so the value of the variable pointer is 0x5200.
X
46. Pointers and ArraysPointers and Arrays
Pointers and arrays are very closely linked in C.Pointers and arrays are very closely linked in C.
Array elements arranged inArray elements arranged in consecutiveconsecutive memory locationsmemory locations
Accessing array elements using pointersAccessing array elements using pointers
int ids[50];int ids[50];
int * p = &ids[0];int * p = &ids[0];
p[i]p[i] <<=>=> ids[i]ids[i]
Pointers and StringsPointers and Strings
A string can be represented by aA string can be represented by a char *char * pointer.pointer.
47. Char name[50];Char name[50];
name[0] = ‘D’;name[0] = ‘D’;
name[1] = ‘a’;name[1] = ‘a’;
name[2] = ‘v’;name[2] = ‘v’;
name[3] = ‘e’;name[3] = ‘e’;
name[4] = ‘0’;name[4] = ‘0’;
char * p = &name[0];char * p = &name[0];
printf(“The name is %s n”, p);printf(“The name is %s n”, p);
NoteNote:: TheThe pp represents the string “Dave”, but not the arrayrepresents the string “Dave”, but not the array
name[50].name[50].
48. Command-Line Argument
In C you can pass arguments to main() function.In C you can pass arguments to main() function.
mmain() prototypeain() prototype
int main(int argc, char * argv[]);int main(int argc, char * argv[]);
argc indicates the number of argumentsargc indicates the number of arguments
argv is an array of input string pointers.argv is an array of input string pointers.
How to pass your own argumentsHow to pass your own arguments??
./hello 10./hello 10
49. What value is argc and argvWhat value is argc and argv??
Let’s add two printf statement to get the value of argc andLet’s add two printf statement to get the value of argc and
argv.argv.
#include <stdio.h>#include <stdio.h>
int main(int main(int argc, char * argv[]);int argc, char * argv[]);))
{{
int i=0;int i=0;
printf("Hello Worldn");printf("Hello Worldn");
printf(“The argc is %d n”, argc);printf(“The argc is %d n”, argc);
for(i=0; i < argc; i++){for(i=0; i < argc; i++){
printf(“The %dth element in argv is %sn”, i, argv[i]);printf(“The %dth element in argv is %sn”, i, argv[i]);
}}
return(0);return(0);
}}
50. The outputThe output
The argc is 2The argc is 2
The 0th element in argv is ./helloThe 0th element in argv is ./hello
The 1th element in argv is 10The 1th element in argv is 10
The trick is the system always passes the name of theThe trick is the system always passes the name of the
executable file as theexecutable file as the firstfirst argument to the main() function.argument to the main() function.
How to use your argumentHow to use your argument??
Be careful. Your arguments to main() are always in string format.Be careful. Your arguments to main() are always in string format.
Taking the above program for example, the argv[1] is string “10”,Taking the above program for example, the argv[1] is string “10”,
not a number. You must convert it into a number before you cannot a number. You must convert it into a number before you can
use it.use it.
51. Data Structure
A data structure is a collection of one or more variables, possibly ofA data structure is a collection of one or more variables, possibly of
different types.different types.
An example of student recordAn example of student record
structstruct stud_record{stud_record{
char name[50];char name[50];
int id;int id;
int age;int age;
int major;int major;
…………
};};
52. A data structure is also a data typeA data structure is also a data type
struct stud_record my_record;struct stud_record my_record;
struct stud_record * pointer;struct stud_record * pointer;
pointer = & my_record;pointer = & my_record;
Accessing a field inside a data structureAccessing a field inside a data structure
my_record.id = 10;my_record.id = 10; “.”“.”
oror
pointer->id = 10;pointer->id = 10; “->”“->”
53. Memory Allocation
Stack memory allocationStack memory allocation
Non-static local variable is an example of stack memoryNon-static local variable is an example of stack memory
allocation.allocation.
Such memory allocations are placed in a system memorySuch memory allocations are placed in a system memory
area called thearea called the stackstack..
Static memory allocationStatic memory allocation
Static local variable and global variable require staticStatic local variable and global variable require static
memory allocation. Static memory allocation happensmemory allocation. Static memory allocation happens
before the program starts, andbefore the program starts, and persistspersists through the entirethrough the entire
life time of the program.life time of the program.
54. Dynamic memory allocationDynamic memory allocation
It allows the program determine how much memory itIt allows the program determine how much memory it
needsneeds atat run timerun time,, and allocate exactly the right amount ofand allocate exactly the right amount of
storage.storage.
The region of memory where dynamic allocation andThe region of memory where dynamic allocation and
deallocation of memory can take place is called thedeallocation of memory can take place is called the heapheap..
NoteNote: the program has the responsibility to free the: the program has the responsibility to free the
dynamic memory it allocated.dynamic memory it allocated.
56. Functions for the dynamic memory allocationFunctions for the dynamic memory allocation
void *malloc(size_t number_of_bytes);void *malloc(size_t number_of_bytes);
allocates dynamic memoryallocates dynamic memory
size_t sizeof(type);size_t sizeof(type);
returns the number of bytes of typereturns the number of bytes of type
void free(void * p)void free(void * p)
releases dynamic memory allocationreleases dynamic memory allocation
An example of dynamic memory allocationAn example of dynamic memory allocation
int * ids;int * ids; //id arrays//id arrays
int num_of_ids = 40;int num_of_ids = 40;
ids = malloc( sizeof(int) * num_of_ids);ids = malloc( sizeof(int) * num_of_ids);
………….. Processing …..... Processing …...
free(ids);free(ids);
57. Allocating a data structure instanceAllocating a data structure instance
struct stud_record * pointer;struct stud_record * pointer;
pointer = malloc(pointer = malloc(sizeofsizeof(struct stud_record));(struct stud_record));
pointer->id = 10;pointer->id = 10;
NeverNever calculate the size of data structure yourself.calculate the size of data structure yourself. TheThe
reason is the size of data types isreason is the size of data types is machine-dependentmachine-dependent.. GiveGive
it to sizeof() functionit to sizeof() function..
size of intsize of int
32-bytes machines32-bytes machines 3232
64-bytes machines64-bytes machines 6464
58. Programming Tips
Replacing numbers in your code with macrosReplacing numbers in your code with macros
- don’t use- don’t use magic numbersmagic numbers directlydirectly
#define MAX_NAME_LEN#define MAX_NAME_LEN 50;50;
char name[MAX_NAME_LEN];char name[MAX_NAME_LEN];
Avoiding global variablesAvoiding global variables
- modulation is more important- modulation is more important
Giving variables and functions a nice nameGiving variables and functions a nice name
- a meaning name- a meaning name
Don’t repeat your codeDon’t repeat your code
- make a subroutine/function- make a subroutine/function
Don’t let the function body to exceed one screenDon’t let the function body to exceed one screen
- hard to debug- hard to debug
59. Indenting your codeIndenting your code (clearance)(clearance)
iif(expression)f(expression)
{{
if(expression)if(expression)
{{
…………
}}
}}
Commenting your codeCommenting your code
Don’t rush into coding. Plan first.Don’t rush into coding. Plan first.
Printing out more debugging informationPrinting out more debugging information
Using debuggerUsing debugger (gdb)(gdb)
60. C vs. C++
C++ is a superset of CC++ is a superset of C
C++ has all the characteristics of CC++ has all the characteristics of C
Using g++ to compile your source codeUsing g++ to compile your source code
61. Books recommended
The C Programming LanguageThe C Programming Language, Brian Kernighan, Brian Kernighan
and Dennis Ritchie. Second edition. Prentice-Hall,and Dennis Ritchie. Second edition. Prentice-Hall,
1988.1988. (C Bible)(C Bible)
The C++ Programming LanguageThe C++ Programming Language, Bjarne, Bjarne
Stroustrup. Third edition. Addison-Wesley, 1997.Stroustrup. Third edition. Addison-Wesley, 1997.
(C++ Bible)(C++ Bible)
Advanced Programming in the UNIXAdvanced Programming in the UNIX
EnvironmentEnvironment,, W. Richard StevensW. Richard Stevens,, Addison-Addison-
Wesley, 1992Wesley, 1992.. (APUE)(APUE)