Introduction
Total Page:16
File Type:pdf, Size:1020Kb
HISTORY, BASIC SYNTAX Introduction 1 2 What is C? Why C? C is a general-purpose programming It’s still popular and widely used language initially developed by Dennis – Available on almost all platforms Ritchie between 1969 and 1973 at – Lots of libraries for different tasks AT&T Bell Labs Provides a relatively low-level (or mid-level) access to the It is an imperative procedural language operating system and hardware intended for system software – System-level programming, embedded systems – Strong ties with UNIX operating system – Can lead to better performance It has influenced many other programming languages – C++, C#, ObjC, Java, JavaScript, Go, csh, ... 3 4 Standards Look and feel First standard by ANSI in 1989, known as “ANSI C” or C89 /* Computing the factorial of an specified (by the user) number */ #include <stdio.h> – Still the best choice when portability is important! int fact(int n); int main(void){ – ISO adopted the same standard in 1990 (C90) int current; printf("Enter some POSITIVE integer (non-positive to finish): "); Next revision in 1999, C99 scanf("%d", ¤t); – New datatypes, complex numbers, variable length arrays,... while (current > 0) { printf("Factorial of %d is %d\n", current, fact(current)); – Not fully backwards compatible with C90 printf("Enter a POSITIVE integer (non-positive to finish): "); scanf("%d", ¤t); Current standard is C11 } return 0; – Improved Unicode support, atomic operations, multi-threading, } bounds-checked functions, ... /* This function returns the factorial of the specified integer (n) */ int fact(int n) { ... 5 6 Basic syntax Formatting Code is case sensitive /* example function */ Free format Statements terminate with ; float foo(int bar) { int i, c = 0; – Whitespace, newlines, layout etc. do not matter … {} enclose blocks float x; x = 0.1; There are two ways to comment: /* example function */ for (i = 0; i < bar; i++) { to the computer ! float foo(int bar) { x += i*3.14 + c; int i, c=0; c = i + 2; /* Single or float x; } /* same example function? */ Multiple lines */ return x; float x = 0.1; } foo(/*float f,*/int bar) { int i,c=0; float x; for (i=0; i<bar; i++) { // Single line (C99) x=0.1;for (/*i=10 x += i*3.14 + c; ; i<2*bar*/ i= c = i + 2; 0;i<bar;i++){x+=i*3.1/*1.2+ } */4+c;c=i+2;}return x;} return x; } 7 8 Basic data types Basic datatypes in C are: char character DATATYPES, VARIABLES, ASSIGNMENT AND OPERATORS int integer number long long integer number float floating point number double double precision float Integers can be signed (default) or unsigned C has also pointer types There is also a special type void 9 10 Variables Variable assignment Variable data types are static // variable declaration Assign a value to a variable: // examples of assignment int i; count = 10; Declare variables before float f, g; variable = value; i = j = 0; double total = 1.9; using them Both should have the same k = i*j + 1; // valid names – data type // assign at declaration C90 requires that the int i3, myINT, I_o; int i = 4; declarations are before any float o3Gf_ry9; – Implicit conversion between other statements // invalid names compatible types // typecast from int to float int 33, 9a, i-o; int i; Valid variable names in C: float o3.Gf; – Explicit conversion (typecast) float f; . Upper and lower case // data type matters syntax: i = 5 * 21; char c; f = (float) i; letters, underline and float f; (type) var numbers are allowed // watch out for operator order f = 1.234; (float) i/5 != (float) (i/5) c = f; // ERROR! // wrong data type 11 12 Arithmetics Compound assignment Operators: addition C has a short-hand notation + // example of compound assignment – subtraction for combined arithmetic int count = 10; count += 5; // now count is 15 * multiplication operation and assignment count /= 3; // and now count is 5 / division Given an operator <op> and // Adding one to count % modulus values a and b, the syntax is count++; a<op>=b and the result is // This is also valid! Operator precedence a=a<op>b ++count; 1) % * / For special cases a+=1 and 2) + - a-=1 there are special Parentheses can be used to group operations () and change operators ++ and -- evaluation order 13 14 Arithmetics and assignment examples Other operators Logical operators Bit-wise operators // addition, substraction // grouping with ()s i = 5 + 2; b = a * (1.3 + (25%3)); i = 5 – 2; && AND >> shift right i += 1; // i = i + 1 // watch out for precedence! || OR << shift left f -= 3.4; f = 1 + q / (1 - q); > larger than & AND i++; // i = i + 1 f = (1 + q) / (1 - q); < less than | OR i--; >= larger or equal ^ XOR // also function calls use () <= less or equal ~ complement // multiplication, division f = r * sin(theta); i = 5 * 2; f = (r + p)*sin(theta); == equal i = 5 / 2; // integer division != unequal f *= 3.0 / 4.2; ! negation // modulus m = 25 % 3; 15 16 Basic I/O printf prints formatted text to the screen Format of printf call is printf(<template> {, <variables>}) BASIC I/O where <template> arbitrary string with optional placeholders for data from variables <variables> (optional) list of variables or values 17 18 Basic I/O Basic I/O example Special characters that can be used in the template string: #include <stdio.h> int main(int argc, char *argv[]) { \n newline \t horizontal tab printf("The answer is %d.\n", 42); \" double quote \\ literal backslash printf("Pi equals to %.2f", 3.14159265); printf(" ...at least to the %dnd decimal.\n", 2); return 0; Placeholders are marked with % followed by formatting and } type information //output: – For now, we will just use the following formattings: // The answer is 42. %d integer value // Pi equals to 3.14 ...at least to the 2nd decimal. %f float value %s string 19 20 Summary Short history and different standards Basic syntax Variables and their type, assignment of values Arithmetic operations Basic IO (printf) 21 POINTERS, ARRAYS AND FUNCTIONS Getting started 22 23 Pointers Pointers On the hardware level a variable is actually a reference to Pointer variables are defined by adding * into the a memory location definition, for example a pointer named ptr of type int The contents of the memory block determine the value is defined as int *ptr; of a variable The address of a variable can be obtained using & – The size of the memory block depends on the type of the operator variable int a; Memory addresses can be stored (and manipulated) Memory using pointers Address Pointer variables can be considered as variables that hold the address of a element with given datatype (int, int *p = &a; char, ...) 24 25 Arrays Array examples // int array of size 10 Static arrays can be introduced using []: int array[10]; // Set value of third element to 1 array[2] = 1; char str[20]; Array of 20 characters // Print the value double values[10]; Array of 10 doubles printf(“a[2]=%d\n”, array[2]); // type of array is equivalent to // type (int*) Elements of array can be accessed using the same [] int *ptr; operator. The value inside brackets is interpreted as an array[0] = 3; ptr = array; offset from the beginning of the array printf(“*ptr=%d\n”, *ptr); – Indices always start from 0 – Last element of an array A of size n is A[n-1] 26 27 Functions Functions are the only subroutine type in C – But functions do not have to return anything Function definitions are of form FUNCTIONS type func-name(param-list) { /* body of function */ } Here type is the return type of the function – void means that function does not return anything 28 29 main function Function example Every C program has the main function with definition This function returns the sum of two integer arguments: #include <stdio.h> int main(int argc, char *argv[]) int add(int a, int b) { { return a + b; /* body of function */ } } int main(void) { Command line arguments are passed to the program int val; using argc and argv val = add(3, 6); main should always return integer printf(“Sum is %d\n”, val); return 0; – zero means success, non-zero values are errors } 30 31 Variable scoping Arguments Variable scoping in C is void funcB(float a) { All arguments are passed as void funcB(int a) { local unless defined int counter; values a += 10; ... } otherwise } Not accessible from funcA – Copy of the value is passed to – Variables declared in int funcA(void) { the function int funcA(void) { the function definition float value_1, value2; – Functions can not change the int var = 0; funcB(value_1); funcB(var); are only visible inside ... value of a variable in the // var is still 0! the function body } calling scope ... – Variables of calling } Not accessible from funcB Pointers can be used to pass a scope are not visible reference to a variable as an inside function body argument! 32 33 C preprocessor The line #include <stdio.h> in the previous example is a preprocessor directive – It directs the preprocessor to literally read in the file PREPROCESSOR stdio.h before the source is passed to the compiler – stdio.h has several definitions related to standard input and output, including the definition of the printf function 34 35 Preprocessor macros and #define #define can be used to define “objects” or macros It has the form of #define identifier replacement-list new-line COMPILING AND LINKING, MATH ROUTINES After the definition, all instances of identifier are replaced with replacement-list // Example #define ONE 1 printf(“Value is %d\n”, ONE); // Result: Value is 1 36 37 Transition from source code to program Let's try it out! Compiling: Write the classic first program in C: #include <stdio.h> – Transforming the C source void main() { #include <stdio.h> int i,j=0; int main(int argc, char *argv[]) { code to machine language float f=1.0; for (i=0; i<8; i++) { foo.c j += i; printf(”Hello, World!\n”); Linker: f *= j+i; } return 0; – Combines object files } generated by the compiler preprocessor Compile your code: into a single executable compiler compiler gcc, cc, ..