1.36k likes | 1.84k Views
C Programming. Philip Fees CS320. Introduction . What made C language popular? What is the future of the C language? Why learn the C language? What does ANSI C mean?. Workshop 1 Topics. Comments Expressions Grouping symbols Identifiers Loops Conditional branching File I/O Basics.
E N D
C Programming Philip Fees CS320 CS320 - C Programming
Introduction • What made C language popular? • What is the future of the C language? • Why learn the C language? • What does ANSI C mean? CS320 - C Programming
Workshop 1 Topics • Comments • Expressions • Grouping symbols • Identifiers • Loops • Conditional branching • File I/O Basics CS320 - C Programming
Comments • English(?) description of program logic • Describe what program is doing not how • /* this is a comment */ • Example: /* increment x until it equals 10 */ int x = 0; while ((x = x + 1) < 10); CS320 - C Programming
Expressions • Statements that are terminated by a semicolon (;) • Evaluation part of loops and conditional branching statements • Have a boolean value (0 = false, non-zero = true) CS320 - C Programming
Grouping Symbols • Way of specifying a set of statements • Pascal uses ‘begin’ and ‘end’ • C uses { and } symbols • Example: if ( x < 10 ) { printf(“An example of grouping statements\n”); printf(“x is less than 10\n”); } CS320 - C Programming
Identifiers • Names of variables and functions • [A-Za-z_][A-Za-z0-9_]* • Examples: get_next, count, setCount, i • Review exercises on page 40 CS320 - C Programming
While Loop • Top testing loop • Syntax: while ( expression ) action • Example: int x = 0; while ( x < 10 ) x = x + 1; CS320 - C Programming
Do Loop • Bottom testing loop • Syntax: do action while ( expression ); • Example: int x = 0; do { x = x + 1; } while (x < 10); CS320 - C Programming
If Statement • Conditional Branch • Syntax: if ( expression ) action • Example: if ( x < 10 ) { printf(“x is less than 10\n”); } CS320 - C Programming
Else Statement • Optional branch of an if statement • Syntax: if ( expression ) action1 else action2 • Example: if (x > 10) printf(“x is greater than 10\n”); else printf(“x is less than or equal to 10\n”); CS320 - C Programming
Nested If Else Statements • Not part of language - readability issue • Syntax: if ( expression1 ) action1 else if ( expresion2 ) action2 else if ( expresionN ) actionN else actionN+1 CS320 - C Programming
File I/O Basics • Include stdio.h, open file, read/write, and close • Example: #include <stdio.h> FILE *fp = fopen(“file”,”r”); int amount; fscanf(fp,”%d”,&amount); fclose(fp); CS320 - C Programming
Workshop 2 Topics • data types • operators • for loop CS320 - C Programming
Data Types • char • short int a.k.a. short • int • long int a.k.a. long • signed, unsigned CS320 - C Programming
Data Types (cont.) • float • double • long double CS320 - C Programming
Arithmetic Operators • + addition, - subtraction, * multiplication, / division, % modulus • -=, *=, /=, %= • precedence (left to right): *, /, %, +, - • (right to left): %=, +=, -=, *=, /= CS320 - C Programming
Relation/Logic Operators • == equal, != not equal, > greater than, >= greater than/equal, < less than, <= less than/equal • Precedence (left to right): <, <=, >, >=, ==, != CS320 - C Programming
For Loop • Top testing loop • Syntax: for ( expression1;expression2;expression3) action • Example: int x; for ( x = 0; x < 10; x = x + 1 ) printf(“%d\n”,x); CS320 - C Programming
Unary Operators • ++ and -- (both prefix and postfix) • Increment (decrement) variable by one unit • Example: int x=1; printf(“++x = %d, x++ = %d\n”,++x,x++); CS320 - C Programming
Workshop 3 Topics • Debugging techniques • Print debugging • Debuggers • Other tools • run time profilers • performance profilers CS320 - C Programming
print debugging • Probably the least efficient technique • Place printf/fprintf at various points in code • Can be enabled/disabled at compile/run time • Can be useful in production trouble shooting • Can affect some types of bugs • Can significantly increase code size CS320 - C Programming
Print Debug Example 1 • Compile time option: /D MYDEBUG (-D on UNIX) #include <stdio.h> … char str[10]; ... #ifdef MYDEBUG fprintf(stderr,”%d@%s: value of str=[%*.*s]\n”,__LINE__, __FILE__,sizeof(str),sizeof(str),str); #endif CS320 - C Programming
Print Debug Example 2 • Compile & Run time #include <stdio.h> … int debugLevel = 1; /* set via command line option */ char str[10]; ... #ifdef MYDEBUG if (debugLevel >= 1) fprintf(stderr,”%d@%s: value of str=[%*.*s]\n”, __LINE__,__FILE__,sizeof(str),sizeof(str),str); #endif CS320 - C Programming
Debuggers • Lets user interact with executing program • Usually part of an integrated development environment or as add-on utility • Most debuggers support basic set features • Difference is in additional features • UNIX adb, sdb, dbx, debugger, etc. • Windows part of Visual, Borland, etc. • Need to keep symbol table (-g UNIX) CS320 - C Programming
Basic Debugger Features • Set break point • Step through program execution • Display/watch variables/address contents • Modify variables/address contents • Step into, over, out of functions • Modify process environment • Display stack trace CS320 - C Programming
Adv. Debugger Features • Attach to running process • Command history and aliases • Memory profiling • Code patching • Expression evaluation • Handling threaded applications • Function execution CS320 - C Programming
Run Time Profilers • Utilities that report information on a process • Bounds checking char str[5]; strcpy(str,”123456789”); • Memory leak - dynamically allocate memory that is never released • Using initialized variables char str[5]; printf(“str=%s\n”,str); • Memory usage stats. CS320 - C Programming
Performance Profilers • Compile time option • UNIX: compile with -p and prof(1) • Windows: see profiling option for environment • Link time utilities • Reports various bits of information • # of time function call • min., avg., max. times • call tree CS320 - C Programming
Workshop 4 Topics • Branch statements • Switch • goto • Casting • Character I/O • Bit operators • formatted printing using printf CS320 - C Programming
Branch Statements • break statement - from innermost loop int strcmp(char str1[], char str2[]) { int idx; /* local index variable */ for (idx = 0; str1[idx] != 0 && str2[idx] != 0; idx++) if (str1[idx] != str2[idx]) break; return str1[idx] - str2[idx]; } CS320 - C Programming
Branch Statements (cont.) • continue statement - resume execution at loop evaluation char str[50]; int idx, count = 0; /* fixed length records */ while (scanf(“%50c”,str) != EOF) { for (idx = 0; idx < 50; idx++) { if (isspace(str[idx])) { idx = 49; continue; } else if (str[idx] == ‘A’) count++; } } CS320 - C Programming
Switch Statement • Restricted version of if, else if, …, else • case values must be constant integer values switch ( integer expression ) { case constant integer 1: statement 1 case constant integer 2: statement 2 … case constant integer n: statement 3 default: /* optional, but typically a good practice */ default statement } CS320 - C Programming
Switch Example • Example: “fall through case” and break switch ( gender ) { case ‘M’: case ‘m’: printf(“male”); break; case ‘F’: case ‘f’: printf(“female”); break; default: printf(“Pat”); break; } CS320 - C Programming
goto Statement • Unconditional transfer to a label • Abused and maligned • Overuse results in spaghetti code • Limited uses include nested loop exit and post processing clean-up • Also useful for single exit point from a function • best to limit scope to within a function CS320 - C Programming
goto Example • Typically database access requires post processing clean-up /* allocate cursors and declare query */ if (error) return FAILED; while (!error) { /* fetch first/next record */ if (error) goto cleanup; /* print record */ } cleanup: /* deallocate cursor */ CS320 - C Programming
Conditional Expression • ternary operator expression1 ? expression2 : expression3 • like an if else statement, but has a value (either expression2 or expression3) • Example: int x, y, quotent; … quotent = y == 0 ? 0 : x / y; /* avoid divide by 0 CS320 - C Programming
Cast Operator • Force value to the given data type • Use with caution: prone to errors long x = 999999; short y = (short)x; /* what is value of y? */ • Example: char str1[10], str2[10]; memcpy((void *)str1,str2,10); CS320 - C Programming
sizeof Operator • Calculates the number of bytes the operand requires. • Example: printf(“sizeof(char)=%d\n”,sizeof(char)); printf(“sizeof(short)=%d\n”,sizeof(short)); printf(“sizeof(int)=%d\n”,sizeof(int)); printf(“sizeof(long)=%d\n”,sizeof(long)); printf(“sizeof(float)=%d\n”,sizeof(float)); printf(“sizeof(double)=%d\n”,sizeof(double)); printf(“sizeof(char *)=%d\n”,sizeof(char *)); char str[15]; printf(“sizeof(str)=%d\n”,sizeof(str)); printf(“sizeof(10)=%d\n”sizeof(10)); CS320 - C Programming
Bitwise Operators • Bit manipulation operators • ~x one’s complement x • x & y bit and x and y • x | y bit or x and y • x ^ y bit exclusive x and y • x << y shift x left y bits • x >> y shift x right y bits • Example: int flags = DEBUG_ON | TRACE_ON; if (flags & DEBUG_ON) ... CS320 - C Programming
getchar and putchar • getchar - get a single character (as an int) from stdin; return EOF at end of input • putchar - put a single character (as an int) to stdout; return character or EOF on error • Example: int c; /* why an int ? */ while ((c = getchar()) != EOF) /* hu? */ if (putchar( c ) == EOF) fprintf(stderr,”putchar(%d) failed\n”,c); CS320 - C Programming
Formatted Printing • #include <stdio.h> • printf(const char *format, arg1, … ,argN) • fprintf(FILE *, const char *format, arg1,…,argN) • All characters are copied to output • % sign begins a conversion code CS320 - C Programming
Formatted Printing (cont.) • Some basic examples: 1) printf(“Hello World!\n”); 2) printf(“Hello\t\tWorld!\n”); 3) printf(“Hello World!\n”); printf(“==== ======\n”); 4) printf(“H\b_e\b_l\b_l\b_o\b_ W\b_o\b_r\b_l\b_d\b_!\b_\n”); CS320 - C Programming
Formatted Printing (cont.) • Conversion Codes • Begins with % sign • Optional flags • Optional positive minimum field width • Optional period • Optional positive precision • Argument code CS320 - C Programming
Formatted Printing (cont.) • Most commonly used conversion codes are c (char), d (char, short, int), f (float/double), s (string) • %c replaced by a single ASCII character • %d replaced by decimal notation string • %f replaced by real number - m.nnnnnn • %s replaced by contents of string CS320 - C Programming
Formatted Printing (cont.) • Some basic examples: 1) printf(“%s\n”,”Hello World!”); 2) printf(“%s\t\t%s\n”,”Hello”,”World!”); 3) printf(“Hello World %d!\n”,6); 4) int i1 = 5; double d1 = 6.78; printf(“i1=%d, d1=%lf\n”,i1,d1); CS320 - C Programming
Formatted Printing (cont.) • Some advanced examples: int i1 = 5; double d1 = 6.78, d2 = 1.2345; 1) printf(“$%.2f $%.2f\n”,d1,d2); 2) printf(“%4.1f\n”,d2); 3) printf(“%*.*f\n”,4,1,d2); 4) printf(“%06d\n”,i1); 5) printf(“%-*d\n”,6,i1); CS320 - C Programming
Formatted Printing (cont.) • Some string examples (from K&R C): char *str = “Hello, World”; /* 12 bytes long */ 1) printf(“[%10s]”,str); /* [Hello, World] */ 2) printf(“[%-10s]”,str); /* [Hello, World] */ 3) printf(“[%20s]”,str); /* [ Hello, World] */ 4) printf(“[%-20s]”,str); /* [Hello, World ] */ 5) printf(“[%20.10s]”,str); /* [ Hello, Wor] */ 6) printf(“[%-20.10s]”,str); /* [Hello, Wor ] */ 7) printf(“[%.10s]”,str); /* [Hello, Wor] */ CS320 - C Programming
Workshop 5 Topics • functions • scope • preprocessor • varargs CS320 - C Programming
Functions • A unit of programming logic that should perform a specific task given a set of values and having a resulting value. • Terminology • is invoked or called • passed arguments • receives parameters • returns a value CS320 - C Programming