CSE 374 Programming Concepts & Tools

Similar documents
CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 C: Linked list, casts, the rest of the preprocessor (Thanks to Hal Perkins)

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 303: Concepts and Tools for Software Development

A Fast Review of C Essentials Part I

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Lecture 2: C Programm

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

BLM2031 Structured Programming. Zeyneb KURT

Procedures, Parameters, Values and Variables. Steven R. Bagley

C Introduction. Comparison w/ Java, Memory Model, and Pointers

CSE 303: Concepts and Tools for Software Development

QUIZ. What is wrong with this code that uses default arguments?

Final CSE 131B Spring 2004


Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

Kurt Schmidt. October 30, 2018

Chapter 11 Introduction to Programming in C

Topic 6: A Quick Intro To C

CSCI 171 Chapter Outlines

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

Chapter 11 Introduction to Programming in C

Short Notes of CS201

C Programming Review CSC 4320/6320

CSE 333 Midterm Exam July 24, Name UW ID#

CS201 - Introduction to Programming Glossary By

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False.

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

QUIZ. Source:

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

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

COMP 2355 Introduction to Systems Programming

CSE 230 Intermediate Programming in C and C++ Functions

Review of the C Programming Language

Motivation was to facilitate development of systems software, especially OS development.

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

QUIZ. What are 3 differences between C and C++ const variables?

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

CSE 303: Concepts and Tools for Software Development

211: Computer Architecture Summer 2016

Chapter 11 Introduction to Programming in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #54. Organizing Code in multiple files

CSE 333 Midterm Exam 7/29/13

CSE 333 Lecture 6 - data structures

G52CPP C++ Programming Lecture 9

Lecture 4 CSE July 1992

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Programming refresher and intro to C programming

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

printf( Please enter another number: ); scanf( %d, &num2);

C++ for Java Programmers

Macros and Preprocessor. CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Motivation was to facilitate development of systems software, especially OS development.

Slide Set 5. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

PRINCIPLES OF OPERATING SYSTEMS

CMSC 330: Organization of Programming Languages

Supporting Class / C++ Lecture Notes

Chapter 11 Introduction to Programming in C

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

EL2310 Scientific Programming

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Exploring the file system. Johan Montelius HT2016

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Have examined process Creating program Have developed program Written in C Source code

Better variadic functions in C

CSE 303 Midterm Exam

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Starting to Program in C++ (Basics & I/O)

CSE 333 Lecture 2 Memory

CS113: Lecture 4. Topics: Functions. Function Activation Records

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

C Programming SYLLABUS COVERAGE SYLLABUS IN DETAILS

Review of the C Programming Language for Principles of Operating Systems

These are notes for the third lecture; if statements and loops.

Chapter 2. Procedural Programming

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

CS16 Exam #1 7/17/ Minutes 100 Points total

Pointers and References

CSE 333 Midterm Exam July 24, 2017 Sample Solution

APS105. Modularity. C pre-defined functions 11/5/2013. Functions. Functions (and Pointers) main. Modularity. Math functions. Benefits of modularity:

CSE 374 Programming Concepts & Tools

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

Transcription:

CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1

The story so far The low-level execution model of a process (one address space) Basics of C: Language features: functions, pointers, arrays Idioms: Array-lengths, strings as arrays with \0 terminators Today a collection of core C idioms/ideas: Control Constructs, ints as booleans Declarations & Definitions Source file structure Two important sublanguages used a lot in C The preprocessor: runs even before the compiler Simple #include and #define for now; more later printf/scanf: formatted I/O Really just a library though Next time: lvalues, rvalues, arrays & pointers; then structs & memory allocation 2

Control constructs while, if, for, break, continue, switch: much like Java Key difference: No built-in boolean type; use ints (or pointers) Anything but 0 (or NULL) is true 0 and NULL are false C99 did add a bool library but not widely used (particularly in old code) goto much maligned, but makes sense for some tasks (more general than Java s labeled break) Gotcha: switch cases fall-through unless there is an explicit transfer (typically a break), just like Java 3

Declarations and Definitions (1) C makes a careful distinction between these two Declaration: introduces a name and describes its properties (type, # parameters, etc), but does not create it ex. Function prototype: int twice(int x); also works (not as good style?): int twice(int); Definition: the actual thing itself ex. Function implementation: int twice(int x) { return 2*x; } 4

Declarations and Definitions (2) An item may be declared as many times as needed although normally at most once per scope or file (i.e., can t declare the same name twice in a scope) Declarations of shared things are often #included (read) from header files (e.g., stdio.h) An item must be defined exactly once e,g., there must be a single definition of each function in only one file no matter how many files contain a declaration of it (or #include a declaration) or actually use it 5

Forward References No forward references allowed: A function must be defined or declared in a source file before it is used. (Lying: implicit declaration warnings, return type assumed int,...) Linker error if something is used but not defined in some file somewhere (including main) Use -c to compile file but not link to others (more later) To write mutually recursive functions, you just need a (forward) declaration 6

Some (more) glitches Declarations must precede statements in a block in classic C But any statement can be a block, so use { } if you need to Or use -std=c11 (or c99) gcc compiler option to relax this restriction 7

Some (more) glitches Array variables in code must have a constant size So the compiler knows how much space to allocate (C99 has an extension to relax this rarely used) Arrays whose size depends on runtime information are allocated on the heap (next time) Large arrays are best allocated on the heap also, even if constant size, although not required 8

More gotchas Declarations in C are funky: You can put multiple declarations on one line, e.g., int x, y; or int x=0, y; or int x, y=0;, or... But int *x, y; means int *x; int y; you usually mean (want) int *x, *y; Common style rule: one declaration per line (clarity, safety, easier to place comments) 9

More gotchas Variables holding arrays have super-confusing (but convenient) rules Array types in function arguments are pointers(!) Referring to an array doesn t mean what you think (!) implicit array promotion (later) 10

The preprocessor Rewrites your.c file before the compiler gets at the code Lines starting with # tell it what to do Can do crazy things (please don t); uncrazy things are: 1. Including contents of header files (now) 2. Defining constants (now) and parameterized macros (textual-replacements) (later) 3. Conditional compilation (later) 11

File inclusion #include <foo.h> Search for file foo.h in system include directories (on Linux /usr/include and subdirs) for foo.h and include its preprocessed contents (recursion!) at this place Typically lots of nested includes, so result is a mess nobody looks at (use gcc -E -P if you want a look!) Idea is simple: e.g., declaration for fgets is in stdio.h (use man for what header file to include) #include "foo.h" the same but first look in current directory How you break your program into smaller files and still make calls to functions other files (more later) gcc -I dir1 -I dir2... look in these directories for header files first (keeps paths out of your code files) we probably won t need to use this 12

Simple macros & symbolic constants #define M_PI 3.14 // capitals a convention to avoid problems #define DEBUG_LEVEL 1 #define NULL 0 // already in standard library Replace all matching tokens in the rest of the file. Knows where words (tokens) start and end (unlike sed) Has no notion of scope (unlike C compiler) (Rare: can shadow with another #define or use #undef) #define foo 17 void f() { int food = foo; // becomes int food = 17; (ok) int foo = 9+foo+foo; // becomes int 17 = 9+17+17; (nonsense) } 13

Typical file layout Not a formal rule, but good conventional style // includes for functions & types defined elsewhere #include <stdio.h> #include localstuff.h // symbolic constants #define MAGIC 42 // global variables (if any) static int days_per_month[ ] = { 31, 28, 31, 30, }; // function prototypes (to handle declare before use ) void some_later_function(char, int); // function definitions void do_this( ) { } char * return_that(char s[ ], int n) { } void some_later_function(char c, int n) { } int main(int argc, char ** argv) { } 14

printf and scanf Just two library functions in the standard library Prototypes (declarations) in <stdio.h> Example: printf("%s: %d %g\n", p, y+9, 3.0) They can take any number of arguments You can define functions like this too, but it is rarely useful, arguments are usually not checked and writing the function definition is a pain Writing these not covered in this course The f in printf is for format crazy characters in the format string control formatting 15

The rules To avoid HYCSBWK*: Number of arguments better match number of % Corresponding arguments better have the right types (%d, int; %f, float; %e, float (prints scientific); %s, \0- terminated char*; (look them up)) Compiler might check, but not guaranteed For scanf, arguments must be pointers to the right type of thing (reads input and assigns to the variables) So int* for %d, but still char* for %s (not char**) int n; char *s; scanf( %d %s, &n, s); *Hopefully You Crash Soon But Who Knows 16

More funny characters Between the % and the letter (e.g., d) can be other things that control formatting (look them up; we all do) Padding (width) %12d %012d Precision... Left/right justification... Know what is possible; know that other people s code may look funny 17

More on scanf Check for errors (scanf returns number of % sucessfully matched) maybe the input does not match the text maybe some number in the input does not parse as a number Always bound your strings Or some external data could lead to arbitrary behavior (common source of viruses; input a long string containing evil code) Remember there must be room for the \0 %s reads up to the next whitespace Example: scanf("%d:%d:%d", &hour, &minutes, &seconds); Example: scanf("%20s", buf) (better have room for 20 characters) 18