Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used to group declarations and.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to C Programming
Programming Languages and Paradigms The C Programming Language.
Macro simple idea of textual substitution useful when you need a group of instructions or directives frequently.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #3 Control.
The Preprocessor Underlying C Language Features Copyright © 2012 by Yong-Gu Lee
Macro Processor.
Chapter 7: User-Defined Functions II
Kernighan/Ritchie: Kelley/Pohl:
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
Homework Any Questions?. Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
Introduction to C Programming
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
 2007 Pearson Education, Inc. All rights reserved C Preprocessor.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 4 Functions and Program Structure Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering.
Fundamentals of C and C++ Programming Control Structures and Functions.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
1 Homework / Exam Finish up K&R Chapters 3 & 4 Starting K&R Chapter 5 Next Class HW4 due next class Go over HW3 solutions.
1 Homework / Exam Turn in HW3 today Exam 1 next class –Open Book / Open Notes –Recommended Use of Book / Notes in Exam: Avoids reliance on “rote memorization”
CPS120: Introduction to Computer Science Decision Making in Programs.
Controlling Execution Dong Shao, Nanjing Unviersity.
Engineering Computing I Chapter 4 Functions and Program Structure.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Week 2-3 Control flow (review) Conditional statements If, else, else if, switch-case, break Loop constructs for, while, do-while, break, continue, label--go;
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
Compiler Directives. The C Preprocessor u The C preprocessor (cpp) changes your source code based on instructions, or preprocessor directives, embedded.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
C++ Functions A bit of review (things we’ve covered so far)
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
Week 3 - Friday CS222.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Java Primer 1: Types, Classes and Operators
C Programming Tutorial – Part I
Programming Languages and Paradigms
Chapter 13 - The Preprocessor
Chapter 12 Variables and Operators
14. THE PREPROCESSOR.
Programming Paradigms
Pre-processor Directives
Variable Names Names are a sequence of visible characters
11/10/2018.
Register Variables Declaring a variable as a "register" variable is an advisory to the compiler to keep the normal location of the variable in a register,
C Preprocessor(CPP).
CSC215 Lecture Control Flow.
Classes and Objects.
Homework Any Questions?.
C Programming Getting started Variables Basic C operators Conditionals
Function.
Homework Finish up K&R Chapters 3 & 4
1-6 Midterm Review.
The C Language: Intro.
Programming Languages and Paradigms
CSC215 Lecture Control Flow.
Function.
Presentation transcript:

Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used to group declarations and statements into a compound statement { x = 0; y = 1; }/* Note: No semicolon after right brace */

if statements, Section 3.2 Shortcut for “equal and not equal to 0” tests Can use: if (expression)if (!expression) In place of if (expression != 0)if (expression == 0)

Else-if, Section 3.3 Consider cascading else-if sequence: if (i == 1) /* NOTE: Only one will execute */ statement-1; else if (i == 2) statement-2;... else if (i == 49) statement-49; else statement-50; /* Default or "catch-all" */

Switch, Section 3.4 Also have switch statement **LIKE JAVA** switch (i) { /* in special limited situations */ case 1: statement-1; break; case 2: statement-2; break;... case 49: statement-49; break; default: statement-50; }

Switch The way the if-else cascade works is to test –Test if i == 1 –If that fails, test if i == 2. If that fails, test if i == –When we test i == 27, we have done 26 prior tests. With the switch statement, we achieve the same effect, but probably faster: –Usually compiled into assembly language as a jump table –Array of "go to" instructions subscripted by the value of i –If i = 27 we "look up" the “go to” at address 27 in table –And execute only that one “go to” –Note the need for break statements. The default action is to cascade down to the code for the next case!!

Loops –while and for, Section 3.5 This “for” statement” for (expr 1 ; expr 2 ; expr 3 ) statement; Is equivalent to this “while” statement: expr 1 ; while (expr 2 ) { statement; expr 3 ; }

For loop Note any part of for loop can be left out. for (init; loop-test; increment) If init or increment expression is left out, just not evaluated (program must initialize and increment by other means) If loop-test is left out, assumes permanently true condition and loops forever. (program must break or goto to end to exit the loop)

Comma operator: "," Most often used in for loop statement Might have been useful for reverse () in hw1 for (i = 0, j = strlen(s) - 1; i < j; i++, j--) Pairs of expressions separated by "," are evaluated left-to-right and type/value of expression is type/value of result. See K & R, pg 53, Precedence Table

Do … While, Section 3.6 The do … while tests at the end of the loop do { statement(s); } while (expression); Executes the statement(s) once even if the “while” loop expression is false upon entry Used much less often than “for” and “while”

Break and Continue, Sections 3.7 The break statement works for: –for loop / while loop / do loop and switch. –Brings you to end of loop or switch statement ONE LEVEL ONLY. The continue statement works for: –for loop / while loop / do loop, but not switch! –It causes next iteration of enclosing loop to begin

GOTO, and Labels, Section 3.8 The goto statement breaks TWO OR MORE levels It “goes to” a statement with a label, e.g. ret: It may be OK to use goto if you always do it in a FORWARD direction. (See axtoi, if use a goto ret; then don't need flag or test in “for” loop.) K&R, pg 66: “goto should be used rarely, if at all.” Note: Project coding standards may prohibit “goto”!

Binary Search /* binsearch: find x in v[0] <= v[1] <=.. <= v[n-1] returns subscript of x if found, -1 if not */ int binsearch ( int x, int v[ ], int n) { int low, high, mid; low = 0; high = n - 1;

Binary Search while ( low <= high) { mid = (low + high)/2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else /* found match */ return mid; } return -1; /* no match */ }

Functions / Program Structure C makes functions efficient and easy to use Program != a few big functions Program = = many small functions Functions may reside in separate source files Source files compiled and loaded separately An Introduction to MAKEFILE is coming (A process that K&R does not go into)

Function Prototypes Return type, function name, and ( ) int foo ( ); float foo ( ); Argument List List of Types and optionally Variable Names int foo (int *, int, float); int foo (int array[], int i, float j); Output arguments usually listed first

Function Prototypes Special case for null argument lists Always code function prototype as: int foo (void); Keeps compiler parameter checking enabled Demonstration of bad example: int foo (); x = foo (i, j, k); /* compiler won’t catch! */

Function Declarations Same as function prototype, except: –Must have variable names in argument list –Followed by { function statements; } not ; Example: int foo (int array[], int i, float j) { function statements; }

Automatic Variables An automatic variable is one normally declared inside the braces of a function: –The scope of the variable is private to the function (accessible within the function braces) –It cannot be referenced from outside the braces –It appears on the stack when the function is called and disappears when the function returns –Undefined (i.e. garbage) value unless explicitly initialized in the source code –It doesn't hold a value between invocations

Static Variables A static variable is declared inside the braces of a function (with keyword static): –The scope of the variable is private to the function (accessible within the function braces) –It cannot be referenced from outside the braces –It does NOT appear on the stack –It is guaranteed to be initialized to zero –It keeps its value across function invocations

External Variables An external variable is one declared outside the braces of any function in the file: –It is accessible by any function in the file –It is private to the file unless you declare same variable name with type "extern" in another file. –It does not appear on the stack –It is guaranteed to be initialized to zero –It holds its value across all function invocations This “global” variable can be troublesome!

Review An external static variable is declared outside of any function (with keyword static), –It is accessible by any function in the file –It is private to the file and cannot be referenced from another file (not even by using “extern”) –It does not appear on the stack –It is guaranteed to be initialized to zero –It holds its value across all function invocations Safer than global variable

Register Variables Declaring a variable as a "register" variable is an advisory to the compiler to keep the normal location of the variable in a register, if possible Gives extra speed for frequently modified variables. There are a limited number of registers in machine (where arithmetic is usually performed -- have to load register from memory location of variable, perform increment/decrement, store value back). Undefined (i.e. garbage) value unless explicitly initialized in the source code

Register Variables void f(int n)void f(register int n){ int i;register int i; for (… ;… ; i++, n--)for (... ;... ; i++, n--) /* during each pass *//* during each pass */ LD r1, &iINCr1(i held in r1) INC r1DECr2(n held in r2) ST r1, &i LDr1, &n DECr1 STr1, &n

Register Variables Advisory only, because number of registers is quite limited, and only in creating the code is it clear what is best. Still, it usually works. A static variable cannot be register type (use register for all time). Can only have automatic variables and formal function parameters (treated like local variables) as register variables. A pointer points to a position in memory. If n is a register variable, can't use “address of”  &n!

C Preprocessor Inclusion of other files – usually.h files #include “filename.h” Simple macro substitution #define name substitute text Macro substitution with arguments #define square(A) ((A)*(A)) enclose in ( )s n = square(x) + 1;  n = ((x)*(x)) + 1; Conditional inclusion

Macros Macros do not understand C expressions. They are only doing precise character substitution. Macro substitution with arguments – bad example #define square(A) A*A If you write in program: n = square(p+1); Macro will be replaced by: n = p+1*p+1; Not what you expected

Macros Macro must be defined on a single line Can continue a long definition to the next line using backslash character (\) #define exchg(t, x, y) {t d; d = x; x = y;\ y = d;} The \ simply tells compiler the following line is a continuation of same logical line

Macros This macro invocation exchg (char, u, v) will be turned into the following text string (shown one statement per line for clarity) {char d; /* Note: d is defined locally within block */ d = u; u = v; v = d; }

Macros Function calls are CALL BY VALUE (can't modify calling program’s argument values inside function unless pointers are passed) This is NOT true for Macros, because statements within a Macro expansion act like in-line code! Frequently used Macro may take more memory than a function, but does not require call/return and stack frames! (Macro will usually execute faster)

Macros Substitutions are not done within quotation marks. If we want to print out the variable makeup of an expression and then the value (e.g., x/y = 17.2), it doesn't work to do it like this: #define dprint(expr) printf("expr = %f\n", expr) …. dprint(x/y); We want: “x/y = 17.2” printed but, it expands as: printf ("expr = %f\n", x/y);

Macros However, using a special convention with the # character. When we define: #define dprint(expr) printf(#expr " = %g\n", expr) The special form #expr means: –Do substitution for the macro “expr” –Put quotes around result Now if we write: dprint(x/y); this expands as: printf("x/y" " = %g\n", x/y); /* two strings concatenated */

Conditional Inclusion Gives control of when precompiler directives such as #define or #include are executed It’s done before compilation with conditionals that are meaningful at that time Conditionals work for any C statements in their scope, and can be used to drop unneeded code (and save memory space) under some conditions

Conditional Inclusion #if (with conditions such as !defined(SYM) #ifdef SYM (like saying #if defined(SYM) #ifndef SYM (like saying #if !defined(SYM) #elif (like else if) #else (like else) #endif (end scope of originating #if)

Conditional Inclusion A software release might need different.h header files included for different O/S's Before main() we might define: #define SYSV 100 #define BSD 101 For a specific system (say SYSV) we write: #define SYSTEM SYSV

Conditional Inclusion Define.h file symbolic constants conditionally: #if SYSTEM = = SYSV #define HDR "sysv.h" #elif SYSTEM = = BSD #define HDR "bsd.h" #else #define HDR "default.h“ #endif #include HDR

Conditional Inclusion Another reason for using conditionals is that some.h files include other headers recursively. It might happen as a result that we include two header files that both recursively include the same.h file This can lead to a compiler warning, maybe even an error, if the a function prototype appears twice during a compilation We DON’T want to include declarations contained in a.h file twice. These conditionals achieve this, when placed inside a header named xxx.h

Conditional Inclusion #ifndef XXX_HDR #define XXX_HDR /* note we don't need to give a value here */ /* next time XXX_HDR will be defined so #ifndef will fail */... (contents of.h file go here) #endif /* XXX_HDR */

Recursion, K&R Section 4.10 Any C function may call itself recursively, either directly or after intermediate function calls Each time a call is made, a new frame is placed on the stack, containing passed arguments, a position to return to, and automatic variables (if any) int factorial (int n) { return (n > 1) ? n * factorial (n - 1) : 1; } Programmer must ensure the recursion terminates!

Recursion, Stack Frames Stack during recursion: int result = factorial (3); factorial (3) factorial (2) factorial (1) Stack Pointer Stack Pointer Stack Pointer Stack Pointer

Code Example blade64(1)% cat recur.c #include int factorial(int); main(){ int m, n=3; m = factorial(n); } int factorial(int k){ int ll; printf("before factorial function: n=%d\n",k); ll = (k > 1) ? k*factorial(k-1): 1; printf(" after factorial function: n=%d\n", k); return ll; } blade64(2)% a.out before factorial function: n=3 before factorial function: n=2 before factorial function: n=1 after factorial function: n=1 after factorial function: n=2 after factorial function: n=3

Recursion, Performance Time relative to while/for loops –Calling/creating stack frame takes a lot of time –Returning/removing stack frame costs time, too Memory relative to while/for loops –Stack frames eat up memory  need large space! –In non-virtual memory system  stack overflow? Recursion is rarely used in hard real-time and/or embedded systems for these reasons