5/24/2016
Resources
• Kochen, Programming in C, Third Edition
Review of Programming • Brian Kernighan and Dennis Ritchie, The C Programming C Language , 2 nd Edition, Prentice Hall – Is considered “THE” book on C : coauthor belongs to the creators of the C programming language – The book is not an introductory programming manual; it assumes some familiarity with basic programming concepts • C Programming Notes by Steve Summit http://www.eskimo.com/~scs/cclass/notes/top.html
Based on the Original Slides from Politehnica International- Computer Engineering Lecture Slides
Compilers The C Programming Language • Developed by Dennis Ritchie at AT&T Bell Laboratories in the early 1970s Source Machine Compiler Code Code • Growth of C tightly coupled with growth of Unix: Unix was written mostly in C • Success of PCs: need of porting C on MS-DOS • Many providers of C compilers for many different platforms => Input Executable Output need for standardization of the C language data Program data • 1990: ANSI C (American National Standards Institute) • International Standard Organization: ISO/IEC 9899:1990
Compiler: analyzes program and • 1999: standard updated: C99, or ISO/IEC 9899:1999 translates it into machine language Executable program: can be run independently from compiler as many times => fast execution
1 5/24/2016
The first C program Compiling and running C programs uses standard library input and output functions Editor (printf) Source code #include
Libraries main: a special name that indicates where the program must begin execution. It is Linker a special function . Executable code file.exe first statement: calls a routine named printf, with argument the string of characters IDE (Integrated “Programming is fun \n” Development last statement: finishes execution of main and return to the system a status value Environment) of 0 (conventional value for OK)
C Compilers and IDE’s Debugging program errors • One can: – use a text editor to edit source code, and then use independent Editor command-line compilers and linkers Syntactic Source code Errors – use an IDE: everything together + facilities to debug, develop and file.c organize large projects • There are several C compilers and IDE’s that support various C compilers Compiler We will use Eclipse and the “GCC” compiler. Object code • file.obj gcc prog.c porg.out
Libraries Linker Executable code file.exe
Semantic Errors
2 5/24/2016
Displaying multiple values Using comments in a program
/* This program adds two integer values and displays the results */ #include
Example: Using data types Basic Data Types - Summary
Type Meaning Constants Ex. printf #include
unsigned 12ull, %llu, long long 0xffeeULL %llx, %llo int
3 5/24/2016
Basic Data Types - Summary (contd.) Integer and Floating-Point Conversions
Type Meaning Constants printf // Basic conversions in C #include
The Type Cast Operator The assignment operators
• f2 = (float) i2 / 100; // type cast operator • The C language permits you to join the arithmetic operators with the • The type cast operator has the effect of converting the value of the variable i2 to assignment operator using the following general format: op=, where op type float for purposes of evaluation of the expression. is an arithmetic operator, including +, –, ×, /, and %. • This operator does NOT permanently affect the value of the variable i2; • op can also be a logical or bit operator => later in this course • The type cast operator has a higher precedence than all the arithmetic operators • Example: except the unary minus and unary plus. count += 10; – Equivalent with: • Examples of the use of the type cast operator: count=count+10; • (int) 29.55 + (int) 21.99 results in 29 + 21 • Example: precedence of op=: (float) 6 / (float) 4 results in 1.5 • a /= b + c • (float) 6 / 4 results in 1.5 – Equivalent with: a = a / (b + c) – addition is performed first because the addition operator has higher precedence than the assignment operator
4 5/24/2016
Program input The while statement
#include
Scanf: similar to printf: first argument contains format characters, next arguments tell where to store the values entered at the keyboard More details -> in a later chapter !
Example – do while Statements break and continue • Programming style: don’t abuse break !!! // Program to reverse the digits of a number #include
5 5/24/2016
Statements break and continue Example: compound relational test
Continue also not so good style!!! // Program to determine if a year is a leap year ... #include
Logical operators Boolean variables
Operator Symbol Meaning // Program to generate a table of prime numbers AND && X && y is true if BOTH x and y are true #include
6 5/24/2016
The switch statement (cont) The conditional operator
Break can miss ! condition ? expression1 : expression2
Statement list on condition is an expression that is evaluated first. a case can miss If the result of the evaluation of condition is TRUE (nonzero), then expression1 ! switch (operator) is evaluated and the result of the evaluation becomes the result of the operation. { If condition is FALSE (zero), then expression2 is evaluated and its result ... becomes the result of the operation case '*': case 'x': maxValue = ( a > b ) ? a : b; printf ("%.2f\n", value1 * value2); break; Equivalent to: ... } if ( a > b ) maxValue = a; else maxValue = b;
Standard input/output Brief overview - scanf()
• The C language itself does not have any special • scanf(control string, list of arguments) • Control string: contains format characters statements for performing input/output (I/O) – Important: match the number and type of format characters with the number operations; all I/O operations in C must be carried and type of following arguments ! – Format characters: as for printf out through function calls . • Arguments: variable names prefixed with the address operator (&) • These functions are contained in the standard C • Example: library. • scanf(“%i %i”,&x,&y); • #include
7 5/24/2016
How scanf works getchar() and putchar()
• Scanf: searches the input stream for a value to be read, bypasses any leading whitespace characters • The simplest input mechanism is to read one • scanf ("%f %f", &value1, &value2); character at a time from the standard input , with • scanf ("%f%f", &value1, &value2); getchar • In both cases, user can type: 3
Example: getchar() Terminating keyboard input
Which character as sign of end of input ? #include
8 5/24/2016
Exercise: getchar() Arrays - Example
/* Read characters from input over several lines until EOF. Example: Count lines and characters in input */ int values[10]; Declares an array of 10 elements of type int #include
Arrays - Example Defining a function
#include
9 5/24/2016
Example: arguments are passed by copying Function prototype values !
• The first line of the function definition #include
Example: scope of local variables Example: function declaration
#include
10 5/24/2016
#include now explained Passing arrays as parameters
• #include
Example: Passing arrays as parameters Array parameters are passed by reference !
// Function to find the minimum value in an array • If a function changes the value of an array element, that change is made #include
11 5/24/2016
Example: multidimensional array as Multidimensional arrays and functions function parameter
• When declaring a single-dimensional array as a formal parameter inside a function, the actual dimension of the array is not needed; simply use a pair of empty The number of brackets to inform the C compiler that the parameter is, in fact, an array. columns must be specified ! • This does not totally apply in the case of multidimensional arrays. For a two- No generic matrix display function possible ! dimensional array, the number of rows in the array can be omitted, but the declaration must contain the number of columns in the array. void displayMatrix (int matrix[3][5]) { • Valid examples: int row, column; for ( row = 0; row < 3; ++row) { function(int array_values[100][50]); for ( column = 0; column < 5; ++column ) function(int array_values[][50]); printf ("%5i", matrix[row][column]); • Invalid examples: printf ("\n"); function(int array_values[100][]); } function(int array_values[][]); }
Global variables Example: global variables
• A global variable declaration is made outside of any function. #include
• Global variables do have default initial values: zero int main(void) { x=7; f1(); f2(); printf(“x=%i \n”,x); }
12 5/24/2016
Automatic and static variables Example: Automatic and static variables
• Automatic local variables : // Program to illustrate static and automatic variables – an automatic variable disappears after the function where it is defined completes execution, the value of that variable disappears along with it. #include
The concept of structures Example: structures
struct date • Structure: a tool for grouping heterogenous elements together. Defines type struct date , with 3 fields of type int { The names of the fields are local in the context • Array: a tool for grouping homogenous elements together int month; of the structure. • Example: storing calendar dates (day, month, year) int day; A struct declaration defines a type: if not followed by a int year; • Version1: using independent variables: list of variables it reserves no storage; it merely }; describes a template or shape of a structure. • int month = 9, day = 25, year = 2004; • Using this method, you must keep track of three separate variables for each date that you use in the program—variables that are logically related. struct date today, purchaseDate; Defines 3 variables of type struct date It would be much better if you could somehow group these sets of three variables together. This is what the structure in C allows you to do ! today.year = 2004; Accesses fields of a variable of today.month = 10; type struct date today.day = 5; A member of a particular structure is referred to in an expression by a construction of the form structurename.member
13 5/24/2016
Example: determine tomorrow’s date (Version 2) Arrays of structures
// Program to determine tomorrow's date struct time { . . . }; #include
Enumerated data type
• You can use the enumerated type to declare symbolic names to represent integer constants. • By using the enum keyword, you can create a new "type" and specify the values it may have. • Actually, enum constants are type int; therefore, they can be used wherever you would use an int. • The purpose of enumerated types is to enhance the readability of a program. • enum primaryColor { red, yellow, blue }; • enum primaryColor myColor, gregsColor; • myColor = red; • if ( gregsColor == yellow ) …
14 5/24/2016
Example: enum The typedef statement
// Program to print the number of days in a month • C provides a capability that enables you to assign an alternate name to a data #include
The typedef statement Inputting character strings
• In forming a typedef definition, proceed as though a normal variable declaration • char string[81]; were being made. Then, place the new type name where the variable name would normally appear. Finally, in front of everything, place the keyword typedef: • scanf ("%s", string); typedef char Linebuf [81]; • The scanf function can be used with the %s format characters to read in a string of • characters up to a blank space, tab character, or the end of the line, whichever • defines a type called Linebuf, which is an array of 81 characters. Subsequently occurs first declaring variables to be of type Linebuf, as in • Note that unlike previous scanf calls, in the case of reading strings, the & is not • Linebuf text, inputLine; placed before the array name ! • If you type in more than 80 consecutive characters to the preceding program typedef struct without pressing the spacebar, the tab key, or the Enter (or Return) key, scanf { overflows the character array ! int month; • scanf has no way of knowing how large its character array parrameters are ! When int day; handed a %s format, it simply continues to read and store characters until one of int year; the noted terminator characters is reached. } Date; • If you place a number after the % in the scanf format string, this tells scanf the maximum number of characters to read. • Correct use of scanf for reading strings: Date birthdays[100]; • scanf ("%80s", string);
15 5/24/2016
Example: string processing String functions
• The C library supplies several string-handling functions; You don’t have to re-write #include
String functions (cont.) Pointers and addresses
• strncat ( s1, s2, n ) • a pointer is a variable whose value is a memory address – Copies s2 to the end of s1 until either the null character is reached or n • int count = 10; characters have been copied, whichever occurs first. Returns s1 . • strncmp ( s1, s2, n ) • int *int_pointer; – Performs the same function as strcmp, except that at most n characters from • int_pointer = &count; the strings are compared. • The address operator has the effect of assigning to the variable int_pointer , • strncpy ( s1, s2, n ) not the value of count , but a pointer to the variable count . – Copies s2 to s1 until either the null character is reached or n characters have been copied, whichever occurs first. Returns s1 . • We say that int_ptr "points to" count • strchr ( s, c ) • The values and the format of the numbers representing memory addresses – Searches the string s for the last occurrence of the character c. If found, a depend on the computer architecture and operating system. In order to have a pointer to the character in s is returned; otherwise, the null pointer is portable way of representing memory addresses, we need a different type than returned. integer ! • strstr ( s1, s2 ) • To print addresses: %p – Searches the string s1 for the first occurrence of the string s2 . If found, a pointer to the start of where s2 is located inside s1 is returned; otherwise, if s2 is not located inside s1 , the null pointer is returned.
16 5/24/2016
Lvalues and Rvalues Declaring pointer variables
type * variable_name; • There are two “values” associated with any variable: – An "lvalue" (left value) of a variable is the value of its address, where • it is not enough to say that a variable is a pointer. You also have to specify it is stored in memory. the type of variable to which the pointer points ! – The "rvalue" (right value) of a variable is the value stored in that – int * p1; // p1 points to an integer variable (at that address). – float * p2; // p2 points to a float • The lvalue is the value permitted on the left side of the • Exception: generic pointers (void *) indicate that the pointed data assignment operator '=' (the address where the result of type is unknown evaluation of the right side will be stored). – may be used with explicit type cast to any type (type *) – void * p; • The rvalue is that which is on the right side of the assignment statement • a=a+1
Indirection (dereferencing) operator * Example: pointers
• To reference the contents of count through the pointer variable int_pointer, you // Program to illustrate pointers use the indirection operator , which is the asterisk * as an unary prefix operator. #include
17 5/24/2016
Using pointer variables NULL pointers
• Values of a pointer variable: • The value of a pointer in C is meaningless until it is set pointing to something ! – Usually the value of a pointer variable is a pointer to some other variable – Another value a pointer may have: it may be set to a null pointer int *p; Severe runtime error !!! the value 4 is stored in the location to • A null pointer is a special pointer value that is known not to point anywhere. *p = 4; which p points. But p, being uninitialized, has a random value, • How to set pointer values:so we cannot know where the 4 will be stored ! • No other valid pointer, to any other variable, will ever compare equal to a null – Using the address operator pointer ! • Predefined constant NULL, defined in
const and pointers Pointers and Function Arguments
• With pointers, there are two things to consider: • If it is necessary that a function alters its arguments, the caller can pass – whether the pointer will be changed pointers to the values to be changed – whether the value that the pointer points to will be changed. • Pointer arguments enable a function to access and change variables in the • Assume the following declarations: function that called it char c = 'X'; char *charPtr = &c; void swap(int *px, int *py) • The pointer variable charPtr is set pointing to the variable c. /* interchange *px and *py */ • If the pointer variable is always set pointing to c, it can be declared as a const pointer as follows: { char * const charPtr = &c; int temp; *charPtr = 'Y'; // this is valid temp = *px; charPtr = &d; // not valid !!! *px = *py; • If the location pointed to by charPtr will not change through the pointer variable *py = temp; charPtr , that can be noted with a declaration as follows: } const char *charPtr = &c; charPtr = &d; // this is valid *charPtr = 'Y'; // not valid !!! int a=3, b=5; swap(&a, &b);
18 5/24/2016
Dynamic memory allocation malloc()
• Whenever you define a variable in C you are reserving one or more •
Examples: malloc Checking what malloc returns !
• When malloc is unable to allocate the requested memory, it returns a null pointer . char *somestring, *copy; Therefore, whenever you call malloc, it's vital to check the returned pointer before ... using it ! copy = (char *) malloc(strlen(somestring) + 1); /* incomplete -- malloc's return value not checked */ strcpy(copy, somestring); int *ip = (int *)malloc(100 * sizeof(int)); if(ip == NULL) { printf("out of memory\n"); return; // exits current function int *ip = (int *) malloc(100 * sizeof(int)); }
int *ip = (int *) malloc(100 * sizeof(int)); if(ip == NULL) { printf("out of memory\n"); exit(1); // exits all nested function calls, // terminates program }
19 5/24/2016
Example: dynamic allocation of arrays Lifetime of dynamic allocated memory
#include free() Binary representation of integers • Dynamically allocated memory is deallocated with the free function. If p contains a pointer previously returned by malloc, you can call • Positive integers: • free(p); 00 0 0 0 0 0 1 0 1 • which will ``give the memory back'' to the heap of memory from which malloc requests are satisfied. • the memory you give back by calling free() is immediately usable by other parts of your program. (Theoretically, it may even be usable by other programs.) most least • When your program exits, any memory which it has allocated but not freed should Sign bit significant or significant or be automatically released by the operating system. high-order bit low-order bit • Once you've freed some memory you must remember not to use it any more. After calling free(p) it is probably the case that p still points at the same memory. However, since we've given it back, it's now ``available,'' and a later call to malloc might give that memory to some other part of your program. 1*2^0+0*2^1+1*2^2=5 20 5/24/2016 Binary representation of integers Bit operators • Negative integers: • & Bitwise AND • | Bitwise Inclusive-OR 11 1 1 1 1 10 1 1 • ^ Bitwise Exclusive-OR • ~ Ones complement • << Left shift most least • >> Right shift Sign bit significant or significant or high-order bit low-order bit • All the operators, with the exception of the ones complement operator ~, are binary operators and as such take two operands. Steps to convert a negative number from decimal to binary: Ex: -5 • Bit operations can be performed on any type of integer value in C—be it 1. add 1 to the value: -5+1=-4 2. express the absolute value of the result in binary: 4=00000100 short, long, long long, and signed or unsigned—and on characters, but 3. then “complement” all the bits: 11111011=-5 cannot be performed on floating-point values . Steps to convert a negative number from binary to decimally: Ex: 11111011 1. complement all of the bits: 00000100 2. convert the result to decimal: 4 3. change the sign of the result, and then subtract 1: -4-1=-5 Usage: Masking bits Usage: Turning bits on • A mask is a bit pattern with some bits set to on (1) and some bits to off (0). • Turn on (set to 1) particular bits in a value while leaving the remaining bits • Example: unchanged. • int MASK = 2; // 00000010, with only bit number 1 nonzero. • Example: an IBM PC controls hardware through values sent to ports. To turn on a • Masking bits: device (i.e., the speaker), the driver program has to turn on the 1 bit while leaving the others unchanged. • flags = flags & MASK; • This can be done with the bitwise OR operator. • all the bits of flags (except bit 1) are set to 0 because any bit combined with 0 • using the & operator yields 0. Bit number 1 will be left unchanged. (If the bit is 1, The MASK has bit 1 set to 1, other bits 0 1 & 1 is 1; if the bit is 0, 0 & 1 is 0.) This process is called "using a mask" because • int MASK = 2; // 00000010, with only bit number 1 nonzero. the zeros in the mask hide the corresponding bits in flags. • The statement • you can think of the 0s in the mask as being opaque and the 1s as being • flags = flags | MASK; transparent. The expression flags & MASK is like covering the flags bit pattern • sets bit number 1 in flags to 1 and leaves all the other bits unchanged. This with the mask; only the bits under MASK's 1s are visible follows because any bit combined with 0 by using the | operator is itself, and any bit combined with 1 by using the | operator is 1. 21 5/24/2016 Usage: Turning bits off Usage: Toggling bits • Turn off (set to 0) particular bits in a value while leaving the remaining • Toggling a bit means turning it off if it is on, and turning it on if it is off. bits unchanged. • To toggle bit 1 in flag : • Suppose you want to turn off bit 1 in the variable flags . • The MASK has bit 1 set to 1, other bits 0 • The MASK has bit 1 set to 1, other bits 0 • int MASK = 2; // 00000010, with only bit number 1 nonzero. • int MASK = 2; // 00000010, with only bit number 1 • flag = flag ^ MASK; nonzero. • You can use the bitwise EXCLUSIVE OR operator to toggle a bit. • The statement: • The idea is that if b is a bit setting (1 or 0), then 1 ^ b is 0 if b is 1 and is 1 if b • flags = flags & ~MASK; is 0. Also 0 ^ b is b, regardless of its value. • Because MASK is all 0s except for bit 1, ~MASK is all 1s except for bit 1. A • Therefore, if you combine a value with a mask by using ^, values corresponding 1 combined with any bit using & is that bit, so the statement leaves all to 1s in the mask are toggled, and values corresponding to 0s in the mask are the bits other than bit 1 unchanged. Also, a 0 combined with any bit unaltered. using & is 0, so bit 1 is set to 0 regardless of its original value. Usage: Checking value of a bit The Left Shift Operator •the bits contained in the value • For example: does flag has bit 1 set to 1? are shifted to the left a number of • you must first mask the other bits in flag so that you compare only bit 1 of flag places (bits) int a=25; with MASK : •Bits that are shifted out through • if ((flag & MASK) == MASK) the high-order bit of the data item printf(“%x %x”,a,a<<1); • are lost, • 0s are always shifted in through the low-order bit of the value. shifted to the left. Associated with this Bit lost 00 0 0 00 0 0 1 1 0 0 1 a : 0x19 0 0 0 0 00 0 1 1 0 0 1 0 a<<1 : 0x32 22