Continued from previous lecture

Similar documents
The Design of C: A Rational Reconstruction: Part 2

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

The Design of C: A Rational Reconstruction (cont.)

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Arithmetic Operators. Portability: Printing Numbers

Standard C Library Functions

Fundamental of Programming (C)

Lecture 02 C FUNDAMENTALS

C programming basics T3-1 -

Standard File Pointers

Computers Programming Course 6. Iulian Năstac


Variables and literals

Work relative to other classes

CSCI 171 Chapter Outlines

Programming for Engineers Iteration

Chapter 3: Operators, Expressions and Type Conversion

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

SECTION II: LANGUAGE BASICS

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Reserved Words and Identifiers

Operators. Java operators are classified into three categories:

Lecture 3. More About C

The Design of C: A Rational Reconstruction" Jennifer Rexford!

File Handling in C. EECS 2031 Fall October 27, 2014

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Fundamentals of Programming

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Contents. A Review of C language. Visual C Visual C++ 6.0

The Design of C: A Rational Reconstruction"

SWEN-250 Personal SE. Introduction to C

Input / Output Functions

Princeton University COS 333: Advanced Programming Techniques A Subset of C90

UNIT 3 OPERATORS. [Marks- 12]

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

ENG120. Misc. Topics

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Advanced C Programming Topics

CS313D: ADVANCED PROGRAMMING LANGUAGE

Course Outline Introduction to C-Programming

The Design of C: A Rational Reconstruction

Expressions and Precedence. Last updated 12/10/18

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Review of the C Programming Language for Principles of Operating Systems

File IO and command line input CSE 2451

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Operators in C. Staff Incharge: S.Sasirekha

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

C - Basics, Bitwise Operator. Zhaoguo Wang

Full file at

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Unit 3. Operators. School of Science and Technology INTRODUCTION

A flow chart is a graphical or symbolic representation of a process.

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Topic 6: A Quick Intro To C

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Quick Reference Guide

These are reserved words of the C language. For example int, float, if, else, for, while etc.

3. Java - Language Constructs I

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Princeton University COS 333: Advanced Programming Techniques A Subset of PHP

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Data Types and Variables in C language

Stream Model of I/O. Basic I/O in C

JAVA OPERATORS GENERAL

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

THE FUNDAMENTAL DATA TYPES

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Lecture 03 Bits, Bytes and Data Types

Operators and Expressions:

ISA 563 : Fundamentals of Systems Programming

File (1A) Young Won Lim 11/25/16

C-LANGUAGE CURRICULAM

LECTURE 3 C++ Basics Part 2

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Expressions & Flow Control

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

PRINCIPLES OF OPERATING SYSTEMS

Informatica e Sistemi in Tempo Reale

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Fundamentals of Programming

The Design of C: A Rational Reconstruction

Accelerating Information Technology Innovation

Review of the C Programming Language

C Basics And Concepts Input And Output

Transcription:

The Design of C: A Rational Reconstruction: Part 2 Jennifer Rexford Continued from previous lecture 2 Agenda Data Types Statements What kinds of operators should C have? Should handle typical operations Should handle bit-level programming ("bit twiddling") Should provide a mechanism for converting from one type to another 3 4 Provide typical arithmetic operators: + - * / % Provide typical relational operators: ==!= < <= > >= Each evaluates to 0 => FALSE or 1 => TRUE Provide typical logical operators:! && Each interprets 0 => FALSE, non-0 => TRUE Each evaluates to 0 => FALSE or 1 =>TRUE Provide bitwise operators: ~ & ^ >> << Provide a cast operator: (type) Aside: Logical vs. Bitwise Ops Logical NOT (!) vs. bitwise NOT (~)! 1 (TRUE) => 0 (FALSE) Decimal Binary 1 00000000 00000000 00000000 00000001! 1 00000000 00000000 00000000 00000000 ~ 1 (TRUE) => -2 (TRUE) Decimal Binary 1 00000000 00000000 00000000 00000001 ~ 1 11111111 11111111 11111111 11111110 Implication: Use logical NOT to control flow of logic Use bitwise NOT only when doing bit-level manipulation 5 6 1

Aside: Logical vs. Bitwise Ops Logical AND (&&) vs. bitwise AND (&) 2 (TRUE) && 1 (TRUE) => 1 (TRUE) Decimal Binary 2 00000000 00000000 00000000 00000010 && 1 00000000 00000000 00000000 00000001 ---- ----------------------------------- 1 00000000 00000000 00000000 00000001 2 (TRUE) & 1 (TRUE) => 0 (FALSE) Decimal Binary 2 00000000 00000000 00000000 00000010 & 1 00000000 00000000 00000000 00000001 ---- ----------------------------------- 0 00000000 00000000 00000000 00000000 Aside: Logical vs. Bitwise Ops Implication: Use logical AND to control flow of logic Use bitwise AND only when doing bit-level manipulation Same for logical OR ( ) and bitwise OR ( ) 7 8 Assignment Operator Assignment Operator What about assignment? Must have a way to assign a value to a variable Many high-level languages provide an assignment statement Would be more succinct to define an assignment operator Performs assignment, and then evaluates to the assigned value Allows assignment expression to appear within larger expressions 9 Provide assignment operator: = Side effect: changes the value of a variable Evaluates to the new value of the variable 10 Assignment Operator Special-Purpose Assignment i = 0; /* Side effect: assign 0 to i. Evaluate to 0. j = i = 0; /* Assignment op has R to L associativity */ /* Side effect: assign 0 to i. Evaluate to 0. Side effect: assign 0 to j. Evaluate to 0. */ while ((i = getchar())!= EOF) /* Read a character. Side effect: assign that character to i. Evaluate to that character. Compare that character to EOF. Evaluate to 0 (FALSE) or 1 (TRUE). */ 11 Should C provide special-purpose assignment operators? The construct i = i + 1 is common More generally, i = i + n and i = i * n are common Special-purpose assignment operators would make code more compact Such operators would complicate the language and compiler 12 2

Special-Purpose Assignment Special-Purpose Assignment Provide special-purpose assignment operators: += -= *= /= ~= &= = ^= <<= >>= (cont.) Provide increment and decrement operators: ++ -- Prefix and postfix forms (1) i = 5; j = ++i; i += j same as i = i + j i /= j same as i = i / j i = j same as i = i j (2) i = 5; j = i++; (3) i = 5; j = ++i + ++i; What is the value of i? Of j? i >>= j same as i = i >> j 13 (4) i = 5; j = i++ + i++; 14 Sizeof Operator Sizeof Operator How can programmers determine data sizes? The sizes of most primitive types are unspecified Sometimes programmer must know sizes of primitive types E.g. when allocating memory dynamically Hard code data sizes => program not portable C must provide a way to determine the size of a given data type programmatically Provide a sizeof operator Applied at compile-time Operand can be a data type Operand can be an expression Compiler infers a data type, on FC010 sizeof(int) => 4 When i is a variable of type int sizeof(i) => 4 sizeof(i+1) sizeof(i++ * ++i 5) What is the value? 15 16 Other What other operators should C have? Function call operator Should mimic the familiar mathematical notation function(arg1, arg2, ) Conditional operator:?: The only ternary operator See King book Sequence operator:, See King book Pointer-related operators: & * Described later in the course Structure-related operators:. -> Described later in the course 17 Summary: C vs. Java Java only >>> right shift with zero fill new create an object instanceof is left operand an object of class right operand? C only -> structure member select * dereference & address of, sequence sizeof compile-time size of 18 3

Summary: C vs. Java Agenda Related to type boolean: Java: Relational and logical operators evaluate to type boolean C: Relational and logical operators evaluate to type int Java: Logical operators take operands of type boolean C: Logical operators take operands of any primitive type or memory address Data Types Statements 19 20 Sequence Statement How should C implement sequence? Decision Compound statement, alias block statement1; statement2; Selection Statements How should C implement selection? if statement, for one-path, two-path decisions if (expr) statement1; if (expr) statement1; else statement2; 0 => FALSE non-0 => TRUE 21 22 Selection Statements (cont.) switch and break statements, for multi-path decisions on a single integerexpr switch (integerexpr) case integerliteral1: break; case integerliteral2: break; default: What happens if you forget break? 23 Repetition Statements How should C implement repetition? while statement; test at leading edge while (expr) statement; for statement; test at leading edge, increment at trailing edge for (initialexpr; testexpr; incrementexpr) statement; dowhile statement; test at trailing edge do statement; while (expr); 0 => FALSE non-0 => TRUE 24 4

Repetition Statements (cont.) Cannot declare loop control variable in for statement for (int i = 0; i < 10; i++) /* Do something */ int i; for (i = 0; i < 10; i++) /* Do something */ Illegal in C Legal in C 25 Other Control Statements What other control statements should C provide? break statement (revisited) Breaks out of closest enclosing switch or repetition statement continue statement Skips remainder of current loop iteration Continues with next loop iteration When used within for, still executes incrementexpr goto statement Jump to specified label 26 Declaring Variables Declaring Variables Should C require variable declarations? : Declaring variables allows compiler to check spelling Declaring variables allows compiler to allocate memory more efficiently : Require variable declarations Provide declaration statement Programmer specifies type of variable (and other attributes too) int i; int i, j; int i = 5; const int i = 5; /* value of i cannot change */ static int i; /* covered later in course */ extern int i; /* covered later in course */ 27 28 Declaring Variables (cont.): Declaration statements must appear before any other kind of statement in compound statement int i; /* Non-declaration stmts that use i. */ int j; /* Non-declaration stmts that use j. */ Illegal in C int i; int j; /* Non-declaration stmts that use i. */ /* Non-declaration stmts that use j. */ Legal in C 29 Computing with Expressions How should C implement computing with expressions? : Provide expression statement expression ; 30 5

Computing with Expressions i = 5; /* Side effect: assign 5 to i. Evaluate to 5. Discard the 5. */ j = i + 1; /* Side effect: assign 6 to j. Evaluate to 6. Discard the 6. */ printf("hello"); /* Side effect: print hello. Evaluate to 5. Discard the 5. */ i + 1; /* Evaluate to 6. Discard the 6. */ Statements Summary: C vs. Java Declaration statement: Java: Compile-time error to use a local variable before specifying its value C: Run-time error to use a local variable before specifying its value final and const Java: Has final variables C: Has const variables Expression statement Java: Only expressions that have a side effect can be made into expression statements C: Any expression can be made into an expression statement 5; /* Evaluate to 5. Discard the 5. */ 31 32 Statements Summary: C vs. Java Compound statement: Java: Declarations statements can be placed anywhere within compound statement C: Declaration statements must appear before any other type of statement within compound statement if statement Java: Controlling expr must be of type boolean C: Controlling expr can be any primitive type or a memory address (0 => FALSE, non-0 => TRUE) while statement Java: Controlling expr must be of type boolean C: Controlling expr can be any primitive type or a memory address (0 => FALSE, non-0 => TRUE) Statements Summary: C vs. Java dowhile statement Java: Controlling expr must be of type boolean C: Controlling expr can be of any primitive type or a memory address (0 => FALSE, non-0 => TRUE) for statement Java: Controlling expr must be of type boolean C: Controlling expr can be of any primitive type or a memory address (0 => FALSE, non-0 => TRUE) Loop control variable Java: Can declare loop control variable in initexpr C: Cannot declare loop control variable in initexpr 33 34 Statements Summary: C vs. Java break statement Java: Also has labeled break statement C: Does not have labeled break statement continue statement Java: Also has labeled continue statement C: Does not have labeled continue statement goto statement Java: Not provided C: Provided (but don t use it!) Agenda Data Types Statements 35 36 6

Should C provide I/O facilities? Unix provides the file abstraction A file is a sequence of characters with an indication of the current position Unix provides 3 standard files Standard input, standard output, standard error C should be able to use those files, and others I/O facilities are complex C should be small/simple Do not provide I/O facilities in the language Instead provide I/O facilities in standard library Constant: EOF Data type: FILE (described later in course) Variables: stdin, stdout, and stderr Functions: 37 38 Reading Characters Reading Characters What functions should C provide for reading characters? Need function to read a single character from stdin And indicate failure Provide getchar() function Define getchar() to return EOF upon failure EOF is a special non-character int Make return type of getchar() wider than char Make it int; that's the natural word size Reminder There is no such thing as the EOF character 39 40 Writing Characters What functions should C provide for writing characters? Need function to write a single character to stdout Provide putchar() function Define putchar() to have int parameter For symmetry with getchar() Reading Other Data Types What functions should C provide for reading data of other primitive types? Must convert external form (sequence of character codes) to internal form Could provide getshort(), getint(), getfloat(), etc. Could provide parameterized function to read any primitive type of data 41 42 7

Reading Other Data Types Provide scanf() function Can read any primitive type of data First parameter is a format string containing conversion specifications Reading Other Data Types '1' '2' '3' 011000010110001001100011 scanf("%d", &i); What is this ampersand? Covered later in course. 00000000000000000000000001111011 123 43 See King book for conversion specifications 44 Writing Other Data Types Writing Other Data Types What functions should C provide for writing data of other primitive types? Must convert internal form to external form (sequence of character codes) Could provide putshort(), putint(), putfloat(), etc. Could provide parameterized function to write any primitive type of data Provide printf() function Can write any primitive type of data First parameter is a format string containing conversion specifications 45 46 Writing Other Data Types 123 00000000000000000000000001111011 printf("%d", i); 011000010110001001100011 '1' '2' '3' Other Issue: What other I/O functions should C provide? fopen(): Open a stream fclose(): Close a stream fgetc(): Read a character from specified stream fputc(): Write a character to specified stream fgets(): Read a line/string from specified stream fputs(): Write a line/string to specified stream fscanf(): Read data from specified stream fprintf(): Write data to specified stream Described in King book, and later in the course after covering files, arrays, and strings See King book for conversion specifications 47 48 8

Summary C design decisions and the goals that affected them Data types Statements I/O facilities Knowing the design goals and how they affected the design decisions can yield a rich understanding of C Appendix: The Cast Operator Cast operator has multiple meanings: (1) Cast between integer type and floating point type: Compiler generates code At run-time, code performs conversion f i = (int)f i 11000001110110110000000000000000 11111111111111111111111111100101-27 -27.375 49 50 Appendix: The Cast Operator Appendix: The Cast Operator (2) Cast between floating point types of different sizes: Compiler generates code At run-time, code performs conversion (3) Cast between integer types of different sizes: Compiler generates code At run-time, code performs conversion f 11000001110110110000000000000000-27.375 i 000000000000000000000000000000102 2 d = (double)f c = (char)i d 11000000001110110110000000000000 00000000000000000000000000000000-27.375 c 00000010 2 51 52 Appendix: The Cast Operator (4) Cast between integer types of same size: Compiler generates no code Compiler views given bit-pattern in a different way i 111111111111111111111111111111102-2 u = (unsigned int)i u 11111111111111111111111111111110 4294967294 53 9