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

Similar documents
Topic 6: A Quick Intro To C

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Programming refresher and intro to C programming

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

A Fast Review of C Essentials Part I

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

Compiler Theory. (GCC the GNU Compiler Collection) Sandro Spina 2009

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code


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

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

EL2310 Scientific Programming

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

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

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

PRINCIPLES OF OPERATING SYSTEMS

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

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

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

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

EL2310 Scientific Programming

ECEN 449 Microprocessor System Design. Review of C Programming

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

CSE 303 Lecture 8. Intro to C programming

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Introduction to C An overview of the programming language C, syntax, data types and input/output

COMP322 - Introduction to C++ Lecture 01 - Introduction

CSCI 171 Chapter Outlines

Compiling and Running a C Program in Unix

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

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

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

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

COMP 202 Java in one week

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

CS3157: Advanced Programming. Outline

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

EL6483: Brief Overview of C Programming Language

BLM2031 Structured Programming. Zeyneb KURT

ANSI C Programming Simple Programs

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

CS240: Programming in C. Lecture 2: Overview


Continued from previous lecture

Exercise Session 2 Simon Gerber

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Programming in C. What is C?... What is C?

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

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

Functions. Using Bloodshed Dev-C++ Heejin Park. Hanyang University

COMP 2355 Introduction to Systems Programming

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

CSE 374 Programming Concepts & Tools

EC 413 Computer Organization

CS Programming In C

Computers Programming Course 5. Iulian Năstac

Data Type Fall 2014 Jinkyu Jeong

Midterm Exam 2 Solutions C Programming Dr. Beeson, Spring 2009

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

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Chapter IV Introduction to C for Java programmers

More on C programming

Lecture 3: C Programm

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

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

Chapter 1 & 2 Introduction to C Language

Bristol Institute of Technology

Computer System and programming in C

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

Input And Output of C++

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

211: Computer Architecture Summer 2016

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

SISTEMI EMBEDDED. The C Pre-processor Fixed-size integer types Bit Manipulation. Federico Baronti Last version:

Variables and literals

EL2310 Scientific Programming

EMBEDDED SYSTEMS PROGRAMMING Language Basics

The Design of C: A Rational Reconstruction: Part 2

ME 461 C review Session Fall 2009 S. Keres

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

Programming Language Basics

Decision Making -Branching. Class Incharge: S. Sasirekha

Should you know scanf and printf?

Contents Lecture 3. C Preprocessor, Chapter 11 Declarations, Chapter 8. Jonas Skeppstedt Lecture / 44

Lectures 5-6: Introduction to C

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

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

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Lectures 5-6: Introduction to C

#include <stdio.h> int main() { printf ("hello class\n"); return 0; }

C for C++ Programmers

Reserved Words and Identifiers

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

Work relative to other classes

Page 1. Agenda. Programming Languages. C Compilation Process

Transcription:

Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions with parameters & results very basic arrays no pointers or structures no string variables (just literal strings) Chapter 1 of C text: overview, don't have to know all details Chapter 2: types, operators & expressions may skip enum constants bitwise operators may be new: please note Chapter 3: control flow may skip: switch, do-while loops Chapter 4: functions (skip section 4.7) Section 7.2 & 7.4: printf & scanf 1 2 "goto Considered Harmful" History Text mentions goto statements in Chapter 3. DO NOT USE!!! Automatic style deduction even on quizzes & final exam. Programming languages evolve! BCPL Β C C++ Java object-oriented 3 4

Versions of C C is an older language & has evolved. Many versions. ANSI C: a standard Most compilers are more flexible than ANSI Rule for this term: Your programs must work using the GNU C compiler. No special flags required. Caution: Make sure your C programs work on the CASLab system. Some other systems use an older compiler Differences Between C and C++ 1. Obvious big difference: no classes in C. Structures only (we'll review later) 2. Some syntax rules are more restrictive in C 3. I/O is different. 4. Different libraries to include 5. Memory allocation is different (later) 6. No bool type 5 6 Compiling and Running a C Program (1) Compiling and Running a C Program (2) For now: one-file programs. File extension must be.c Suppose my program is hello.c To get a nicer name for executable: gcc -o greeting hello.c Now executable file is called greeting (no extension) gcc command: GNU Compiler Collection File extension tells compiler which language. Simplest way to compile & run: gcc hello.c Produces an executable file called a.out. 7 8

Compiling and Running a C Program (3) Two-step method: gcc -c hello.c Compiles only. Does not link. Produces hello.o ("object code") To get an executable (link object code with C library): gcc -o greeting hello.o Warnings Recommended flag for gcc: -Wall Enables many helpful warnings. Examples: single = inside a conditional wrong number of arguments for printf or scanf forgetting to return a value from a function that's not void unused variables Not required for CISC 220, but very helpful in debugging. Suggestion: alias gcc="gcc -Wall" 9 10 One-Line Comments Strict ANSI C: no one-line comments (//) All comments are /*... */ gcc compiler allows one-line comments, so OK to use for CISC 220. Control Structures Just like Java: if, while, for One difference with for loops: In C++ & Java, OK to declare for loop counters in loop: for (int i = 1; i <= 10; i++)... Standard C does not allow this. Instead: int i; for (i = 1; i <= 10; i++)... 11 12

Booleans Signed vs. Unsigned No bool/boolean type in C. Results of tests are integers. 0 = false non-zero = true Be very careful about "=" vs "==": int x = 2; if (x = 3) printf("yes"); else printf("no"); printf("%d\n",x); Integers may be specified signed or unsigned. Default is signed. Integers on CASLab: 4 bytes (32 bits) Signed integer on CASLab: -2 31 to 2 31-1 Unsigned integer on CASLab: 0 to 2 32-1 13 14 Bitwise Operations in C Example: File Protections Logical operators on sequences of bits. View an integer as a string of booleans -- each bit is true (1) or false (0). &: bitwise and : bitwise or ~: bitwise not ("one's complement") 0110 1100 = 1110 0110 & 1100 = 0100 ~0110 = 1001 Goal: store read/write/execute protection for a file in one integer (instead of three separate integers) #define READ 4 #define WRITE 2 #define EXECUTE 1 int main() { int file1perm = READ WRITE; int file2perm = READ EXECUTE; int common = file1perm & file2perm; // remove write permission from file1 file1perm = file1perm & ~WRITE; 15 16

Integer Division Rules: arithmetic between two ints: result is an int (division is truncated) arithmetic between int & float or two floats: result is a float (no truncation) use "(float)" to cast an int into a float printf C++ programmers: The >> operator is part of C++, not C. To write characters to the screen (standard output) in C, use the printf function. Simple use to write a message: printf("hello, world\n"); Ending with \n is important: no equivalent of Java's println. 17 18 printf Conversion Specifications printf Field Widths: Integer To include the value of a variable in output, use special conversion codes in first parameter: %d: integer (d for "decimal", not "double"!) %u: unsigned int %ld: long %lu: unsigned long %f: float or double %c: single character %s: string Example: int x =...; float y =...; printf("the answers are %d and %f\n", x, y); May put minimum field width after a %: printf("%5d\n", num); pads with left blanks if necessary 19 20

printf Field Widths: floating point For float and double, may also specify a precision: printf("%8.2f\n", x); Minimum of 8 characters total Exactly two digits after decimal point scanf Reads from the standard input. Conversion specifications similar to print, not exactly the same! type printf scanf char %c %c int %d %d float %f %f double %f %lf Return value from scanf: EOF if hit end of file before reading values otherwise, number of values read 21 22 Portability Issues Sizes of numeric types differ, depending on compiler & target machine. C arithmetic is not portable! sizeof(type): number of bytes used by the type <limits.h>: contains constants giving max & min values for the integer types <float.h>: constants relating to floating-point types Look at sizes.c... Floating-Point Types Basic floating-point type: float Other types: double, long double All floating point numbers are signed. 23 24

Arrays (quick preview) To create an array of 20 integers: int nums[20]; Things to note: no "new" array elements are not initialized no ".length" C Functions and Program Structure Reading: Chapter 4 of C text You may skip Section 4.7 (register variables) Included in this sub-topic: functions, parameters and return results multi-file programs the C preprocessor (no macros with arguments) example: array1.c Things to remember array parameters passed by reference (address of array) type of array parameter doesn't include size example: array2.c 25 26 Functions Functions in C very similar to Java/C++ All parameters are passed by value (no "ref" parameters in C) main Function A C program must have a main function. Optional parameters to main: later (command-line args) Return type of main is int: return status. Good practice when writing C programs that may be run in Linux: return 0 for success, non-zero for error aborts To abort a program from a function that's not main: exit(1) (exit function is in <stdlib.h>) 27 28

Order of Declarations In C, every function & variable must be declared before it is used. In smallfunc.c, defined functions in convenient order: each function fully defined before called. Not always possible or convenient: mutual recursion preferences about order of functions in files separate compilation Declaration vs. Definition Declaration of function tells you: name of function return types number and types of parameters A specification: not how the function works but how to use it. Declaration == header only Sometimes called a "forward declaration" Definition of function: full definition, including the body. All details of how the function works. Includes repetition of information from declaration. Definition = header + body 29 30 Global Variables Variables defined outside any functions. Must be declared before use. Use with caution: can make program much less readable! Example: add global count & accuracy to smallfuncs.c The C Pre-processor Two phases of C compilation: source code pre-processor modified source code compiler object code 31 32

Pre-Processor Language Every line starting with "#" is a command to the pre-processor. Important: Pre-processor syntax C syntax! To run pre-processor by itself: cpp P <filename> #define (note: We're skipping macros with arguments section 6.3.3) #include #undef #if #ifdef #ifndef #else #elif #endif Pre-Processor Directives examples... 33 34 Notes and Reminders #include's can nest to any depth Preprocessor will complain if you define something that's already defined use #undef first (or check with #ifdef) #if/#ifdef useful to comment out a block of code temporarily (avoids problems with nested comments) #if & #ifdef also useful to implement different "modes" for example debugging and non-debugging mode, or linux and Windows mode arithmetic in #if expressions is integer arithmetic #include <filename>: look in system directories #include "filename": look in current directory Pre-Processor Definitions with gcc gcc -DNAME=VALUE program.c Caution: if NAME is already defined in program.c you'll get a warning. 35 36

Separating Programs Into Files Java: very simple, by classes. C: program is a sequence of definitions (mostly functions) separate definitions into multiple files no automatic scheme for where to find functions Why Multiple Files? 1. Large programs: faster compilation *** 2. Logical organization related definitions grouped together 3. Working in groups each programming editing a different file 4. Library files definitions useful in more than one program *** Goal: be able to compile each file separately. Later, link compiled portions of program together. 37 38 module.h: void func1(int x); int func2(float y); program.c: #include "module.h"... int main() {.. func1(17); z = func2(3.4); } /* end main */ Usual Style module.c: #include module.h void func1(int x) {... (function body) } int func2(float y) {... (function body) } Demonstration Split smallfuncs.c into several files: one file contains input function another file contains square root function and helpers other file contains main function 39 40

To Compile One File a Partial Program To Link a Program Together gcc Wall c module.c Can use gcc to link several object files together: Output is module.o: object code machine code with some pieces unspecified (i.e. references to other parts of the program) gcc o program file1.o file2.o file3.o executable file created by combining all the object code & resolving references between them 41 42 Possible Changes to Demo Program 1. Change square root function (use different algorithm) 2. Change detail in main file 3. Add a second parameter to the square root function 4. Add cube root function (used by main) 43