C Language Part 1 (Minor modifications by the instructor)
References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian, and Dennis Ritchie, Prentice Hall, 1988 2
Compilers vs Interpreters Compiler Generates a file containing the translation of the program into the machines native code. Does not actually execute the program Interpreter Reads and performs (executes) the program file directly read translate execute cycle me@computer:~$ gcc my_program.c me@computer:~$./a.out GCD: 8 3
C Functions All C code must be nested within functions C program: a list of function definitions Functions cannot be nested within each other Function definition: type of its return value, its name, a list of arguments, block of code main function A special C function where the program execution begins 4
C Statements A C statement ends with ; or a block statement 1. int x; // declarations 2. x = y + z ; // expressions as statements 3. printf( hello, world ); // expression 4. return 0; 5. if (x<0) { printf( negative! ); } 6. while (i >= 0) { i--; printf(i); } 7. for (i=0; i<10; i++) { printf(i);} 5
Block Statement Also known as a compound statement It is a statement, but does not need to end with ; A group of any number of declarations and statements Surrounded by a pair of curly braces Treated as a single statement Can be nested A variable declared within a block has block scope An identifier is active and accessible from its declaration point to the end of the block If an identifier is redeclared in an inner block, the original declaration is hidden by the redeclaration in the inner block from the redeclaration point to the end of the inner block 6
7
Whitespaces Space, newline, tab Only have meaning in separating words and operators 1 whitespace = 100 whitespaces = 1000 disc = b * b - 4 * a * c; if (disc < 0) { num_sol = 0; } else { t0 = -b / a; if (disc == 0) { num_sol = 1; sol0 = t0 / 2; } else { num_sol = 2; t1 = sqrt(disc) / a; sol0 = (t0 + t1) / 2; sol1 = (t0 - t1) / 2; } } disc=b*b-4*a*c;if(disc<0){ num_sol=0;}else{t0=-b/a;if( disc==0){num_sol=1;sol0=t0/2 ;}else{num_sol=2;t1=sqrt(disc/a; sol0=(t0+t1)/2;sol1=(t0-t1)/2;}} 8
C Declarations Names (identifiers) in C Case sensitive Contain digits and underscores (_), but may not begin with a digit In C, all identifiers must be declared before they are used Type information for storage allocation by the compiler Help the compiler to choose correct operations 9
Declarations (contd.) To declare a variable, specify the type of the variable, and then its name The variable can have an initial value Multiple variables can be declared after the type by separating them with commas 10
Data Type The name that specifies the kind of data values Determines The possible values in the category The operations that can be performed on the values The way the values can be stored Used by the compiler 11
Fundamental Types in C There are several basic data types in C: char: a single byte holding one character int: an integer typically having the integer size of the host machine float: single-precision floating point double: double-precision floating point 12
C Variables A named storage location that contains some value The name is bound to the location 13
C Assignment Operation Denoted by = Assigns the value of the right-hand side operand to the storage location bound to the left-hand side operand For example, x = y stores the value stored in the storage location bound to y to the storage location bound to x 14
C Pointers A reference to a variable The location (address) of the variable in the memory A pointer is a variable that stores a reference to another variable It is said to point to the variable Used in programs to access memory and manipulate addresses The basic syntax to declare a pointer is a type name followed by * and an identifier int *x; x is a pointer to an integer x contains the address of an integer variable or value A null pointer has a special value (NULL) reserved for indicating that it does not refer to any valid object int *x = NULL; 15
Reference Operator address of operator The reference (address) of a variable is obtained by preceding the variable with & 16
Dereference Operator value pointed by operator Pointer dereferencing Obtaining the value stored in the location which the pointer points to Preceding the pointer with * If a NULL pointer is dereferenced then a run-time error will occur and execution will stop likely with a segmentation fault 17
Void Type The type for the result of a function that does not return anything The type of a pointer which does not point to any particular type For example, void *x; The pointer contains an address and the compiler has no idea what type of object the pointer points to To indicate that a function does not take any parameters int foo(void) int foo() // equivalent to the above 18
Local Variables Local variables A variable declared inside a function Function parameters A variable declared inside a block Not visible to other functions Each local variable in a function or a block comes into existence when the function is called or the block is entered, and it disappears when the function or the block is exited The memory space for a local variable is allocated in the associated function s stack frame Called automatic variables Exists solely for the duration of the stack frame 19
Non-local Variables in C Exist for all time from the beginning of program execution to the end of the execution Accessible to all functions 20
21
C Constants An integer constant is a decimal integer like 75 and -492 A floating point constant contains a decimal point like 3.14 or an exponent like 4e-1 (which means 0.4) A character constant is one character within single quotes like a 22
C Constants (contd.) A qualifier const can be applied to any variable declaration to specify that its value will not be changed any more const float pi = 3.14; pi cannot be assigned to a new value 23
C Arithmetic Operators + Addition - Subtraction * Multiplication / Division If both of its operands are integers, / gives the quotient The value of 9/4 is 2 % Remainder It requires integer operands and gives the remainder The value of 9%4 is 1 24
True and False in C 0 (zero) evaluates to false and any other number to true 25
C Relational Operators < less than > greater than <= less than or equal to >= greater than or equal to == equal to!= not equal to Returns either 0 (false) or 1 (true) The value of 7 < 9 is 1 The value of 7 > 9 is 0 26
C Logical Operators! Logical NOT && Logical AND Logical OR Returns either 0 or 1 27
Operator Precedence The unary! operator has the same precedence as the unary + and operators, and they have higher precedence than any binary operators Expressions connected by && or are evaluated left to right, and evaluation stops as soon as the result is determined i > 0 && n / i == 10 means (i > 0) && ((n / i) == 10) Short circuit evaluation In (i > 0 && n / i == 10), if i>0 is false, the rest needs not to be evaluated Highest * / % + - < > <= >= ==!= && Lowest 28
Type Conversion in C Type conversions can occur across an assignment or when the operands of a binary operator are evaluated To choose a proper machine instruction to perform the operation An expression (such as x + y) has both a value and a type To perform a binary operation, its operands must be of the same type When two operands are of different types, generally the more restricted operand is converted to the more general one 29
Type Conversion (contd.) Examples int i; float f; In i + f, the operand i gets promoted to a float and the expression i + f as a whole has type float double d; int i; In d = i, i is converted to double and assigned to d Other names: automatic conversion, implicit conversion, coercion, promotion, widening 30
Type Conversion (contd.) char c; short s; int i; long l; unsigned u; unsigned long ul; float f; double d; long double ld; c s/i (int) u*3.0-i (double) c+4 (int) c+3.0 (double) d+s (double) 7*i/l (long) u*4-i (unsigned) f*8-i (float) 8*s*ul (unsigned long) ld + c (long double) u-ul (unsigned long) 31
Type Casts Explicit type conversion by the programmer Examples (double) i (long) ( A + 1.0) (double) (x = 22) (float) i + 3 ((float) i) + 3 d = (double) i / 5 32
Increment and Decrement Operators C has special operators for increment (add by 1) and decrement (subtract by 1), ++ and -- They can be used as prefix operators like ++i or postfix operators like i++ ++i increment i before its value is used, while i++ increments after its value is used Assume i has the value 7 n = ++i; sets n to 8 n = i++; sets n to 7 In both cases, i becomes 8 ++ and -- have higher precedence than any binary operators 33
printf Function prototypes A way of declaring functions int foo(int a); float bar(void); Printf s prototype is included in stdio.h Printf is passed a list of arguments: a format string and other arguments The format string contains both ordinary characters and conversion specifications (format specifiers) 34
printf (contd.) printf( abcde ); printf( %s, abcde ); printf( %c%c%c%c%c, a, b, c, d, e ); printf( %c%4c%4c, a, b, c ); c d e f g s Character Decimal integer Floating-point number in scientific notation Floating-point number In the e-format or f-format, whichever is shorter string 35
printf (contd.) 36
scanf Analogous to printf, but used for input scanf is passed a list of arguments: a format string and other arguments Other arguments Addresses scanf( %d, &x); The format specifier %d is matched with &x Treat characters in the input stream as a decimal integer and store it at the address of x 37
scanf (contd.) When reading numbers, white spaces (blanks, newlines, and tabs) are skipped, but when reading in a character, they are not c d f Character Decimal integer Floating-point number (float) LF or lf Floating-point number (double) s string 38
scanf (contd.) 39
Call by Value Arguments to functions are always passed by value When a function is called, the value of each real argument is assigned to the corresponding formal parameter, and any changes in a formal parameter does not affect the value of the associated real argument The expression passed as an argument to a function is first evaluated, and its value is passed to the function a b c 4 3 5 + 7 5 x y foo(a + b, c); int foo(int x, int y) 40
Call by Value (contd.) 41
Swap 42
Swap (contd.) 43