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

Slides:



Advertisements
Similar presentations
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Advertisements

CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
CSE 303 Lecture 16 Multi-file (larger) programs
Lecture 2 Introduction to C Programming
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
CS16 Week 2 Part 2 Kyle Dewey. Overview Type coercion and casting More on assignment Pre/post increment/decrement scanf Constants Math library Errors.
CSc 352 An Introduction to the C Preprocessor Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
CS Winter 2011 Introduction to the C programming language.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
CS 201 Functions Debzani Deb.
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:
Guide To UNIX Using Linux Third Edition
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Computer Science 210 Computer Organization Introduction to C.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Week 3 Part I Kyle Dewey. Overview Odds & Ends Constants Errors Functions Expressions versus statements.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Programming language
Compiler Construction
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.
Learners Support Publications Classes and Objects.
Introduction to Programming
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
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.
Chapter 21: The Standard Library Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 21 The Standard Library.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
CS 261 – Data Structures Introduction to C Programming.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Semantics CSE 340 – Principles of Programming Languages Fall 2015 Adam Doupé Arizona State University
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
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.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 18 – Linking and Libraries.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 13 – C: The Rest of the Preprocessor.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
User-Written Functions
Computer Science 210 Computer Organization
CSE 374 Programming Concepts & Tools
CSE 303 Concepts and Tools for Software Development
CSE 374 Programming Concepts & Tools
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Basics.
Programmazione I a.a. 2017/2018.
Computer Science 210 Computer Organization
Chapter 11 Introduction to Programming in C
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).
Classes and Objects.
Programming in C Miscellaneous Topics.
CSc 352 An Introduction to the C Preprocessor
Programming in C Miscellaneous Topics.
Chapter 11 Programming in C
Programming Languages and Paradigms
The Three Attributes of an Identifier
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
SPL – PS1 Introduction to C++.
Presentation transcript:

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

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 not link yet (more later) –To write mutually recursive functions, you just need a (forward) declaration 6

Some (more) glitches Declarations must precede statements in a “block” –But any statement can be a block, so use { … } if you need to –Or use -std=c11 (or c99) gcc compiler option 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 7

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) 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) 8

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) 9

File inclusion #include Search for file foo.h in “system include directories” (on Fedora /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 if you want a look!) –Idea is simple: e.g., declaration for fgets is in stdio.h (use man for what 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 10

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” 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 = ; (nonsense) } 11

Typical file layout Not a formal rule, but good conventional style // includes for functions & types defined elsewhere #include #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) { … } int main(int argc, char ** argv) { … } 12

printf and scanf “Just” two library functions in the standard library –Prototypes (declarations) in 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 13

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); 14

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 15

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) 16