Chapter 11 Introduction to Programming in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 11-2 Compilation.

Slides:



Advertisements
Similar presentations
Chapter 11 Introduction to Programming in C
Advertisements

C Programming Day 1 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12.
Chapter 11-14, Appendix D C Programs Higher Level languages Compilers C programming Converting C to Machine Code C Compiler for LC-3 Please return breadboards.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Overview C programming Environment C Global Variables C Local Variables Memory Map for a C Function C Activation Records Example Compilation.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
Chapter 11-12, Appendix D C Programs Higher Level languages Compilers C programming Converting C to Machine Code C Compiler for LC-3.
Chapter 11-12, Appendix D C Programs Higher Level languages Compilers C programming Converting C to Machine Code C Compiler for LC-3.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
C Stack Frames / Pointer variables Stack: Local Variables Pass & Return values Frame Ptr linkage (R5) and PC linkage (R7) Pointer Variables: Defining &
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Computer Science 210 Computer Organization Introduction to C.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
High-Level Programming Languages: C++
1 C Programming Language Review and Dissection I: Overview, Static and Automatic Variables, and Program Control Flow These lecture notes created by Dr.
Chapter 12 Variables and Operators. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Basic C Elements.
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
Chapter 11 Programming in C Compilation vs. Interpretation Different ways of translating high-level language Compilation translates code into machine.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Chapter 12 Variables and Operators. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Basic C Elements.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
CMPE13Cyrus Bazeghi 1 Chapter 12 Variables and Operators.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9-2 JSR Instruction Jumps to a location (like.
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Declarations (aka prototype) int.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
CMPE13Cyrus Bazeghi 1 Chapter 11 Introduction to Programming in C.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
C is a high level language (HLL)
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Bill Tucker Austin Community College COSC 1315
The Machine Model Memory
Computer Science 210 Computer Organization
Chapter 12 Variables and Operators
Chapter 12 Variables and Operators
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
ICS103 Programming in C Lecture 3: Introduction to C (2)
Introduction to C Programming
Chapter 12 Variables and Operators
Chapter 12 Variables and Operators
Computer Science 210 Computer Organization
Chapter 11 Introduction to Programming in C
Introduction to C Programming
Chapter 11 Introduction to Programming in C
Chapter 11 Introduction to Programming in C
Chapter 11 Programming in C
Chapter 12 Variables and Operators
Chapter 11 Introduction to Programming in C
Presentation transcript:

Chapter 11 Introduction to Programming in C

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Compilation vs. Interpretation Different ways of translating high-level language Interpretation interpreter = program that executes program statements generally one line/command at a time limited processing easy to debug, make changes, view intermediate results languages: BASIC, LISP, Perl, Java, Matlab, C-shell Compilation translates statements into machine language  does not execute, but creates executable program performs optimization over multiple statements change requires recompilation  can be harder to debug, since executed code may be different languages: C, C++, Fortran, Pascal

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Compilation vs. Interpretation Consider the following algorithm: Get W from the keyboard. X = W + W Y = X + X Z = Y + Y Print Z to screen. If interpreting, how many arithmetic operations occur? If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Compiling a C Program Entire mechanism is usually called the “compiler” Preprocessor (No Java equivalent) macro substitution conditional compilation “source-level” transformations  output is still C Compiler generates object file  machine instructions Linker combine object files (including libraries) into executable image

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Multi-Pass Compiler Source Code Analysis (Java does this) “front end” parses programs to identify its pieces  variables, expressions, statements, functions, etc. depends on language (not on target machine) Code Generation (JVM or JIT does this) “back end” generates machine code from analyzed source may optimize machine code to make it run more efficiently very dependent on target machine Symbol Table map between symbolic names and items like assembler, but more kinds of information

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Compiling and Linking Various compilers available cc, gcc includes preprocessor, compiler, and linker Lots and lots of options! level of optimization, debugging preprocessor, linker options intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc gcc –S file.c // to spit out the assembly file (.s) gcc –c file.c // spits out the object file (.o) gcc file.c // produces a.out gcc –o myprogram file.c // “-o” allows you to name output

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Major differences between C and Java Preprocessor allows for efficient naming of constants No String or boolean types Keyboard input and monitor output static, public, and private are slightly different Memory allocation – must deallocate memory explicitly No objects in C – though we can group data together. How references / pointers are used Most other differences are minor.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display A Simple C Program #include #define STOP 0 /* Function: main */ /* Description: counts down from user input to STOP */ int main(int argc, char *argv[]) { /* variable declarations */ int counter; /* an integer to hold count values */ int startPoint; /* starting point for countdown */ /* prompt user for input */ printf("Enter a positive number: "); scanf("%d", &startPoint); /* read into startPoint */ /* count down and print count */ for (counter=startPoint; counter >= STOP; counter--) printf("%d\n", counter); } Equivalent to “import” Preprocessor directive Equivalent to String[] args No “static public” Declarations are the same Printing a screen Reading from the keyboard Printing an integer

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Preprocessor Directives #include These are the most common library files in C To make your functions visible to other code, place prototype into a.h file  no restrictions -- could be any C source code #define STOP 0 Before compiling, preprocessor replaces all instances of the string "STOP" with the string "0" Called a macro Used for values that won't change during execution, but might change if the program is reused. (Must recompile.) Lots and lots of other uses – we might learn some later

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Comments Begins with /* and ends with */ Can span multiple lines Cannot have a comment within a comment Comments are not recognized within a string example: "my/*don't print this*/string" would be printed as: my/*don't print this*/string // - style commenting is C++. Some C compilers accept it. As before, use comments to help reader, not to confuse or to restate the obvious

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display main Function Every C program must have a function called main(). argc contains the number of arguments argv is an array of char pointers (array of strings), just like in Java main(int argc, char *argv[]) { /* code goes here */ }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Variable Declarations – Just like Java int counter, startPoint; Predefined types in C: int integer (at least 16 bits) – short, long double floating point (at least 32 bits) char character (at least 8 bits) Sizes are influenced by register sizes of computer. Declaring arrays in C: int myArray[5]; Declaring references (pointers) in C: int *myArray; Dereferencing a pointer: myArray[0] = 5; *myArray = 5; Note: In Java, references are tied to the type. No references to primitive types, only references to objects.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Literals Integer 123 /* decimal */ x123 /* hexadecimal */ Floating point e23 /* x */ 5E12 /* 5.0 x */ Character 'c' '\n' /* newline */ '\xA' /* ASCII 10 (0xA) */

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Bitwise Operators – the same as Java SymbolOperationUsage PrecedenceAssoc ~ bitwise NOT ~x 4r-to-l << left shift x << y 8l-to-r >> right shift x >> y 8l-to-r & bitwise AND x & y 11l-to-r ^ bitwise XOR x ^ y 12l-to-r | bitwise OR x | y 13l-to-r Operate on variables bit-by-bit. Like LC-3 AND and NOT instructions. Shift operations are logical (not arithmetic). Operate on values -- neither operand is changed.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Logical Operators – Same syntax as Java Different semantics since C has no boolean values SymbolOperationUsage PrecedenceAssoc ! logical NOT !x 4r-to-l && logical AND x && y 14l-to-r || logical OR x || y 15l-to-r Treats entire variable (or value) as TRUE (non-zero) or FALSE (zero). Result is 1 (TRUE) or 0 (FALSE).

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Input and Output Variety of I/O functions in C Standard Library. Must include to use them. printf("%d\n", counter); String contains characters to print and formatting directions for variables. This call says to print the variable counter as a decimal integer, followed by a linefeed ( \n ). scanf("%d", &startPoint); String contains formatting directions for looking at input. This call says to read a decimal integer and assign it to the variable startPoint. (Don't worry about the & yet.)

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display More About Output Can print arbitrary expressions, not just variables printf("%d\n", startPoint - counter); Print multiple expressions with a single statement printf("%d %d\n", counter, startPoint - counter); Different formatting options: %d decimal integer %x hexadecimal integer %c ASCII character %f floating-point number %s string (char *)

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Examples This code: printf("%d is a prime number.\n", 43); printf("43 plus 59 in decimal is %d.\n", 43+59); printf("43 plus 59 in hex is %x.\n", 43+59); printf("43 plus 59 as a character is %c.\n", 43+59); produces this output: 43 is a prime number. 43 plus 59 in decimal is plus 59 in hex is plus 59 as a character is f.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Examples of Input Many of the same formatting characters are available for user input. scanf("%c", &nextChar); reads a single character and stores it in nextChar scanf("%f", &radius); reads a floating point number and stores it in radius scanf("%d %d", &length, &width); reads two decimal integers (separated by whitespace), stores the first one in length and the second in width Must use ampersand ( & ) for variables being modified. This is the symbol for “address of” because it needs to know where to place the input.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Scope in Java – For those who know Java class MyClass { public static int globalItem; private static int onlyISeeGlobal; int myFunction() { int localItem; if (true) { int localItem; // hides early variable } // if true } // end of myFunction } // end of MyClass public – everyone can see it static – always exists private – only MyClass code sees it static – always exists Only exists while in if statement Hides earlier variable Only exists during function call Only accessible within function call

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Scope: Global and Local Where is the variable accessible? Global: accessed anywhere in program Local: only accessible in a particular region Compiler infers scope from where variable is declared programmer doesn't have to explicitly state Variable is local to the block in which it is declared block defined by open and closed braces { } can access variable declared in any "containing" block Global variable is declared outside all blocks

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example #include int itsGlobal = 0; main() { int itsLocal = 1; /* local to main */ printf("Global %d Local %d\n", itsGlobal, itsLocal); { int itsLocal = 2; /* local to this block */ itsGlobal = 4; /* change global variable */ printf("Global %d Local %d\n", itsGlobal, itsLocal); } printf("Global %d Local %d\n", itsGlobal, itsLocal); } Output Global 0 Local 1 Global 4 Local 2 Global 4 Local 1

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example #include int itsGlobal = 0; main() { int itsLocal = 1; /* local to main */ printf("Global %d Local %d\n", itsGlobal, itsLocal); { itsLocal = 2; /* local to this block */ itsGlobal = 4; /* change global variable */ printf("Global %d Local %d\n", itsGlobal, itsLocal); } printf("Global %d Local %d\n", itsGlobal, itsLocal); } Output Global 0 Local 1 Global 4 Local 2 Global 4 Local 2

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Scope Example 2 #include int nextCount(); // function prototype so compiler knows it exists main() { int itsStatic = 5; printf(“Counter: %d %d\n", nextCount(), itsStatic++); printf(“Counter: %d,%d\n", nextCount(), itsStatic++); printf(“Counter: %d\n", nextCount()); } int nextCount() { static int itsStatic = 0; return ++itsStatic; } Output Counter: 1, 5 Counter: 2, 6 Counter: 3 Counter: 4 only visible in this function static – always exists

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Scope Example 2 #include int nextCount(); // function prototype so compiler knows it exists main() { int itsStatic = 5; printf(“Counter: %d %d\n", nextCount(), itsStatic++); printf(“Counter: %d,%d\n", nextCount(), itsStatic++); printf(“Counter: %d\n", nextCount()); } int nextCount() { static int itsStatic = 0; return itsStatic++; } Output Counter: 0, 5 Counter: 1, 6 Counter: 2 Counter: 3 only visible in this function static – always exists

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Making variables visible to other programs Must be a global variable where allocated declared extern in other file extern int otherGlobal; Common practice: Place “extern int otherGlobal” in code.h file Place “int otherGlobal” in code.c file Anyone who wants to use otherGlobal includes code.h: #include “code.h” Note: There can only be one instance of “int otherGlobal” declared globally throughout all files. All global variables must have distinct names.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Local Variable Storage Local variables are stored in an activation record, also known as a stack frame. Symbol table “offset” gives the distance from the base of the frame. R5 is the frame pointer – holds address of the base of the current frame. A new frame is pushed on the run-time stack each time a block is entered. Because stack grows downward, base is the highest address of the frame, and variable offsets are <= 0. seconds minutes hours time rate amount R5

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Allocating Space for Variables Global data section All global variables stored here (actually all static variables) R4 points to beginning Run-time stack Used for local variables R6 points to top of stack R5 points to top frame on stack New frame for each block (goes away when block exited) Offset = distance from beginning of storage area Global: LDR R1, R4, #4 Local: LDR R2, R5, #-3 instructions global data run-time stack 0x0000 0xFFFF PC R4 R6 R5

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Variables and Memory Locations In our examples, a variable is always stored in memory. When assigning to a variable, must store to memory location. A real compiler would perform code optimizations that try to keep variables allocated in registers. Why?

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example: Compiling to LC-3 #include int inGlobal; main() { int inLocal; /* local to main */ int outLocalA; int outLocalB; /* initialize */ inLocal = 5; inGlobal = 3; /* perform calculations */ outLocalA = inLocal++ & ~inGlobal; outLocalB = (inLocal + inGlobal) - (inLocal - inGlobal); /* print results */ printf("The results are: outLocalA = %d, outLocalB = %d\n", outLocalA, outLocalB); }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example: Symbol Table NameTypeOffsetScope inGlobalint0global inLocalint0main outLocalAintmain outLocalBint-2main

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example: Code Generation ; main ; initialize variables AND R0, R0, #0 ADD R0, R0, #5 ; inLocal = 5 STR R0, R5, #0 ; (offset = 0) AND R0, R0, #0 ADD R0, R0, #3 ; inGlobal = 3 STR R0, R4, #0 ; (offset = 0)

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example (continued) ; first statement: ; outLocalA = inLocal++ & ~inGlobal; LDR R0, R5, #0 ; get inLocal ADD R1, R0, #1 ; increment STR R1, R5, #0 ; store LDR R1, R4, #0 ; get inGlobal NOT R1, R1 ; ~inGlobal AND R2, R0, R1 ; inLocal & ~inGlobal STR R2, R5, #-1 ; store in outLocalA ; (offset = -1)

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example (continued) ; next statement: ; outLocalB = (inLocal + inGlobal) ; - (inLocal - inGlobal); LDR R0, R5, #0 ; inLocal LDR R1, R4, #0 ; inGlobal ADD R0, R0, R1 ; R0 is sum LDR R2, R5, #0 ; inLocal LDR R3, R5, #0 ; inGlobal NOT R3, R3 ADD R3, R3, #1 ADD R2, R2, R3 ; R2 is difference NOT R2, R2 ; negate ADD R2, R2, #1 ADD R0, R0, R2 ; R0 = R0 - R2 STR R0, R5, #-2 ; outLocalB (offset = -2)