1 / 69

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

Review of the C Programming Language (with some new material). Last revised: Jan 3, 2019. 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

mallett
Download Presentation

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) Last revised: Jan 3, 2019

  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, long, long long, float, double, long 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 effect as the above line *(stringPtr+0) = ‘J’; *(stringPtr+6) = ‘Z’; //becomes “Jello Zorld” void *anything; //Not a pointer to nothing. A pointer to any type!

  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 = &people[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. Initializing members of an Array C99 allows us to specify particular elements int nums[100]={1,2,3,4,5, [50]=42,[22]=0}; The last subscript changes more quickly int matrix[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};

  17. 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

  18. 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];

  19. Initializing data in a declaration float icecream=2.1f; double mint=2.1; char name[]={“Hello Central”}; The last subscript changes more quickly 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'}};

  20. C99 extensions to initialization C99 allows us to specify particular elements int nums[100]={1,2,3,4,5, [50]=42,[22]=0}; C99 lets us define fields out of their regular order struct PERSON peter={“Peter Jones”, .sex=‘M’, .age=22 };

  21. 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); }

  22. /* 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 &)

  23. 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)

  24. 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

  25. 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

  26. 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

  27. 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 } }

  28. Declaration Modifiers • auto variable automatically released when the function or block of code is exited. 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.

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

  30. 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);

  31. 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

  32. 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 () ?

  33. 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);

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

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

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

  37. 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;

  38. 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”); }

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

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

  41. 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

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

  43. 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

  44. 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)

  45. 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 }

  46. 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 ....

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

  48. 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

  49. 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

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

More Related