1 / 67

Review of the C Programming Language (with some new material)

Review of the C Programming Language (with some new material). If you know Java you know most of C. Common Programming Language Features. Comments Data Types Variable Declarations Expressions Flow of Control Statements Functions and Subroutines Macros and Preprocessor Commands

hueym
Télécharger la présentation

Review of the C Programming Language (with some new material)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Review of the C Programming Language(with some new material)

  2. If you know Javayou know most of C

  3. Common Programming Language Features • Comments • Data Types • Variable Declarations • Expressions • Flow of Control Statements • Functions and Subroutines • Macros and Preprocessor Commands • I/O Statements • Libraries • External Tools (Compiler, debugger etc)

  4. Comments in C • comments are the most important feature in any programming language because comments assist with debugging!!! • Comments should precede any block of code or any code that might be difficult to understand. A comment should describe the intent of what you are trying to do. • Write your comments BEFORE you write your code. Do not rely on the code itself to document what you are doing as the code may be incorrect • Comments may also be used to temporarily remove a block of code from your program /* This is a comment it can span many lines */ //Single line comments

  5. Primitive Data Types • Primitive data types are built into the language • They are scalar (single valued) variables • data types are: char, int, float, double, bool and pointer

  6. Ordinal Constants in C • char : ‘A’, ‘AB’, ‘ABCD’ • int: -200, • 1000000L • (unsigned) 127 • 0x80FA (hex), • 007 (octal) • 0 (false) • non-zero (true) * range of values depends on word size of the machine. Usually 4 bytes for a long int. “ordinal” means countable – there is a next value.

  7. Special Character Constants • ‘\n’ - newline • ‘\r’ - carriage return • ‘\t’ - tab • ‘\\’ - backslash • ‘\’’ - quoted apostrophe • ‘\”’ –quoted quote • ‘\0’ – null character • ‘\a’ – audible alert • ‘\b’ - backspace

  8. Pointers • *(0xF00AA00)&myVariable • Pointers are ordinal (countable) types • A pointer is an address in memory • a pointer points to the start of a block of memory • sizeof pointer depends on the addressable range of the machine. (can have 2, 4, 6 or even 8 byte pointers)

  9. Non-Ordinal Constants • float : 12.5E-12. -0.5 • double: 12.5E+200 always use doubles, not floats

  10. Non-Primitive Data Types • contain multiple values • arrays • structs • unions

  11. Declaring Scalar Variables • short cake; • int i; • unsigned int value; • long face; • float icecream; • double mint; • char *myPointer; • enum suit {club, diamond, heart, spade} cardSuit;

  12. Pointer Notation Read these symbols as follows: • & - the address of • * - value of the location pointed to by /* Example 1 - read it aloud */char x[10]= {“Hello World”};char * stringPtr;stringPtr = x; stringPtr = &x[0]; /* same thing as the above line*/ *(stringPtr+0) = ‘J’; *(stringPtr+6) = ‘Z’; /* x becomes “Jello Zorld” */

  13. Pointers and Arrays are (almost) the Same The following statements do exactly the same thing: X[5] = 7; *(x+5) = 7; *(5+x) = 7; 5[x] = 7; //Yes, this is legal in C!

  14. Pointer Notations with structs • . - the member variable • -> that points to /* Example 2 – read it aloud to aid understanding */ struct PERSON { char name[10]; int age; char sex; };struct PERSON people[10];struct PERSON *ptrPerson;people[3].sex = ‘F’;ptrPerson = &list[3];ptrPerson -> age = 24;(We’ll see this later with passing parameters to functions)

  15. Declaring Arrays • char name[20]; • double matrix[10][12]; • int cube[5][5][5]; The dimensions of an array are always constants The values of subscripts range from 0 to n-1 C just calculates an offset from The base of the array – there is no bounds checking!!!!

  16. Strings are implemented as Arrays char name[]={“Hello World”}; • double quotes are used, not single quotes • strings are terminated by a null character • unicode (2 byte characters) is not well supported

  17. Declaring Structs A struct is a new data type made up of other data types (including other structs) struct Person { char name[10]; unsigned int age; double income unsigned short nKids; char * next; }; struct Person joe,ellen, voters[20];

  18. Initializing data in a declaration float icecream=2.1f; double mint=2.1; char name[]={“Hello Central”}; int matrix[3][4]= { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}}; char names[][10] = {"Andrea", "Bob", "Singh"}; struct PERSON { char name[10]; int age; char sex; } ; struct PERSON list[] = { {"Sally",21,'F'}, {"Rex",20,'M'}};

  19. A subroutine is a function does not directly return a value void mySubroutine(double x) { fprintf(stdout,”Hello: %lf\n”, x); return; } You should declare a function before its first use. If you don’t the assumption is that it returns an int int indexOf(const char *, char); int indexOf(const char * string, char c) { //content of function goes here } Declaring Functions A function returns a value double fn(double x) {return x*2;} A function without a return type is assumed to return a type of integer fn2(double x,double y) { return (int) (x+y); }

  20. /* Only arguments passed by value result in a change to the original parameter */ void fn1(int arg1) { arg1++; //arg1 does not change outside } //of fn1 because it’s a copy void add1 (int * arg1) { (*arg1)++; // arg1 changes in calling } // routine too. num=21; fn1(num); /* fn1 can’t change num */ add1(&value); /* fn2 does change num */ Passing arguments in functions • values are passed either by address(also called by reference) or by value • primitive variables and constants are passed by value. fn1 gets a copyof the variable, not the original • floats are always passed as doubles and converted back to floats. • putting an & in front of a value means it will be passed by address • arrays are always passed by address without adding the & • structs are always passed (copied) by value (unless you add the &)

  21. The Truth about Passing Arguments to Function All arguments in C are passed by value.Its just that some values happen to be addresses char name[20]; double cross; result=myFunction(name); result2=myFunction(&cross)

  22. int main(int argc, char * argv[], char * envp[]) { int i; /* print out the command line arguments */ fprintf(stdout,”\nCommand Line args\n\n”); for(i=0; i<argc; i++) fprintf(stdout,”argv[%d]: %s”, i, argv[i]); /* print out the environment variables */ fprintf(stdout,”\n\nEnvironment Variables\n”); for(i=0; envp[i]; i++) fprintf(stdout,”envp[%d]: %s, value: %s\n”, i, envp[i], getenv(envp[i])); return 0; } main is a special function main is the name of the function that starts your program. It has 3 arguments and it returns an 8 bit integer value that represents the completion status code of your program to the host operating system. A return value of zero indicates program success. A non-zero return value indicates some kind of failure, but you decide on the meaning of the code. The 3 arguments to main are: • argc the number of arguments in the command line. • *argv[ ] an array of strings. Each entry in the array points to a different command line argument argv[0] refers to the name of the program argv[1] refers to the 1st command line argument argv[2] refers to the 2 argv[argc] is null • *envp[ ] an array of strings. Each entry in the array points to a different environment variable. The last entry is null

  23. Functions are data types too A function is just an address in memory. A function is a data type that represents a block of code int myFunc() { return 20; } fprintf(stdout, “myFunc is located at address %x\n”, myFunc); 0x0AF00080: myFunc

  24. Advanced: Storing functions in variables int function1(double x) { return (int)(x*x); } int function2(double y) { return (int)(-y); } … //Declaring the function pointer int (*functionPtr)(double); //Standard notation: portable functionPtr=function1; fprintf(stdout,”Eg1: %d\n”,(*functionPtr)(5.7)); //Non-standard notation: less portable functionPtr=function2; fprintf(stdout,”Eg2: %d\n”,functionPtr(5.7)); function1 (*functionPtr) functionPtr stores the address of function1 or function2 as needed

  25. Callback Functions The syntax can be a little tricky but passing functions to functions is fairly common to systems programming. Functions passed to functions are called “callback functions”. Void mySort(void * values, int (*compare)(void * a, void *b), size_t size, int nItems) { … if( (*compare)( values[i*size],values[j*size]) { //swap } }

  26. Additional Declaration Modifiers • void * variable is a pointer to a subroutine • auto variable automatically released when the function or block of code is exitted. The keyword is unnecessary as all variables are automatically considered auto • static variable is retained as long as the program is being run. Opposite of auto. • externthe variable was created elsewhere - outside the current function or outside the current file • volatilethe variable can be modified by another program or a physical device. A warning to the compiler not to apply optimization techniques to the variable. • registerA suggestion to the compiler that the variable is used frequently and should be stored in a CPU register rather than in conventional RAM memory. This is supposed to optimize the program. Compilers usually ignore this suggestion so it rarely works. • const Indicates that the value will never change after its initial declaration. Wnen used with a function parameter it indicates that the function will never change the value.

  27. Operators in C • Assignment: = • Arithmetic : * / + - ++ -- % • Logical: && || ! • Relational: > < == <> • Bitwise: & | ^ << >> ~ • Pointer: -> * ** • Grouping: () [] , • Triadic: (cond) ? value1 : value2

  28. Operators in C • Operators can be binary or unary. • ?: is a special triadic operator. • Any binary operator can be combined with the assignmentoperator, ie:a*=3;is the same as a=a*3; • Assignment isn’t special – its an operator like any other a=b+(c=7);

  29. Priority Operator Description 1 ()[].-> Parentheses (grouping)Brackets (array subscript)Member selection Member selection via pointer 2 ++  --+  -!  ~(type)*&sizeof   Unary pre/post increment/ decrementUnary plus/minusUnary logical negation/bitwise complementUnary cast (change type)DereferenceAddress of size in bytes 3 *  /  % times/divide/mod 4 +  - plus, minus 5 <<  >> bitwise left shift, bitwise right shift 6 <  <=>  >= less than, less than or equal to greater than, greater than or equal 2 7 == != equal to, not equal to 8 & bitwise and 9 ^ bitwise xor 10 | bitwise or 11 && || logical and, logical or (short circuit operators 12 = += -= *= /= %= &= |= ^= <<== >>= Arithmetic Assignment Bitwise assignment 13 , comma: sequence operator Expressions: Operator Precedence

  30. Expressions: Operator Precedence • When in doubt use brackets () • If you know the correct operator precedence, but aren’t so sure others will know it as well – use use brackets () • use brackets to make your meaning clear ( : - ) • did I mention you should use () ?

  31. Expressions: Type Precedence • float + double  double • float + int  float • short * long  long • char + int  int • address + int  address When 2 operands are of different types, the result is the larger or more complicated type When in doubt of the result, use the cast operator result = (float) (myDouble + myInt);

  32. Expressions: Type Precedence Remember: x = 1/4; /* x  0 */ x = 1.0/7; /* x .25*/ C does very little type checking!!

  33. Flow of Control: IF stmt if(condition) stmt; else stmt; if(x>10) puts(“Too Big”); else puts(“Value OK”);

  34. Flow of Control: if stmt if(x>10 && x<20) { /* block of code */ } else { /* another block of code */ }

  35. Secret Slide The triadic operator is a shorter form of if/then/else examples: if(x>10) y=2; else y=0; y= (x>10) ? 2 : 0 if(x>10) fprintf(stdout,”X is big\n”); else fprintf(stdout,”X is small\n”); fprintf(stdout, (x>10) ? “X is big\n” : “x is small”); if(a>b) return a; else return b; return (a>b) ? a : b;

  36. Flow of Control: switch/case switch(ordinalValue) { case ‘A’: case ‘a’: puts(“A chosen”); break; case 2: puts(“# 2 choice”); break; default: puts(“None of the above”); }

  37. while(condition) { int localValue; doStuff(); } Variables can be declared at the start of any block of code { } Flow of Control: while

  38. while(true) { int localValue; doStuff(); } Variables can be declared at the start of any block of code { } Forever loop: while

  39. do { doStuff(); } while(condition); This kind of loop is always executed at least once. The test is at the end of the loop Flow of Control: do while

  40. Flow of Control: for loops for(initialization; condition; increment) { doStuff(); ... } initialization

  41. for(i=0;i<10;i+=2) { for(init; cond; incr) { .... some code ... if(condition1) break; ... if(condition2) continue; } } break: exits the inner loop continue: jump to the end of the inner loop and loops around again The break and continue statements

  42. for(int i=0;i<10;i++) {} for(i=10;i; i--) {} for(;i;i--) {} for(;condition;) {} for(;;) {} Unlike java you can’t declare a variable inside the initialization section – unless .... gcc –std=gnu99 myprog.c Ordinal values can be used as conditions Each field of the for stmt is optional leaving out the condition makes the for stmt loop for ever Flow of Control: For Loops (cont’d)

  43. for loops: Common Patterns • iterating through a stringfor(i=0;string[i];i++) fputc(string[i], outFile); • iterating through a linked list{ struct LLIST * temp; for(temp=head; temp; temp=temp->next) fprintf(stdout,”Value: %s\n”, temp->value }

  44. Flow of Control: Labels and the dreaded Goto • You probably were not taught about the goto statement • If you were, you were told that it was bad • use break, continue, exit(n) instead • Use it only in emergencies ....

  45. Flow of Control: An example of goto for ( ...) for(...) { if(errorCond) goto errorLabel; } errorLabel: fprintf(stderr,”Bad mojo – quitting program”);

  46. A macro can be used to define a value #define PI 3.141529 #define TRUE 1 #define FALSE 0 #define MAX_FILES 26 A macro can be used to define an expression #define max(a,b) (a>b?a: b) #define display(a) (fprintf(stdout, “The value is: %d \n”, a); display(max(x[i+j],x[i+k)); Macros

  47. insert text from a file Preprocessor Commands: Conditional Compilation #include <stdio.h> #include “myInc.h” #define DEBUG #ifdef DEBUG fprintf(stdout,”Value of x is: %d\n”,x); #else /* Do nothing */ #endif

  48. I/O C has no I/O commands. All I/O is performed using library functions

  49. Character & String I/O • fputc(int c,FILE *stream); • fputs(const char *s, FILE * stream) • int putc(int c, FILE * stream); • int putchar(int c); • int puts(const char *s); • int fgetc(FILE *stream); • char fgets(char *s, int size,FILE *stream); • int getc(FILE *stream); • int getchar(void); • char *gets(char *s); • int ungetc(intc FILE *stream); A positive return value is the value read or written. A negative return value is interpretted as an error code.

  50. Formatted IO: Don’t Use printf(“fmt string”, varList....) scanf(“fmt string”, &varList...) Don’t use these any more

More Related