Programming in C and C++

Similar documents
Structure of this course. C and C++ Past Exam Questions. Text books

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

Programming in C and C++

Presented By : Gaurav Juneja

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

Programming in C and C++

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

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

Object-Oriented Programming

The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

Work relative to other classes

C and C++ 2. Functions Preprocessor. Alan Mycroft

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C-LANGUAGE CURRICULAM

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

Control flow and string example. C and C++ Functions. Function type-system nasties. 2. Functions Preprocessor. Alastair R. Beresford.

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

Chapter 1 & 2 Introduction to C Language

Computers Programming Course 5. Iulian Năstac

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

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

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

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

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

A Fast Review of C Essentials Part I

Review of the C Programming Language for Principles of Operating Systems

6.096 Introduction to C++ January (IAP) 2009

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Outline. 1 About the course

Chapter 1 Introduction to Computers and C++ Programming

Fundamental of C programming. - Ompal Singh

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

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Differentiate Between Keywords and Identifiers

CE221 Programming in C++ Part 1 Introduction

Axivion Bauhaus Suite Technical Factsheet MISRA

EL2310 Scientific Programming

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

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

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

UNIT- 3 Introduction to C++

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

C Programming Multiple. Choice

C: How to Program. Week /Mar/05

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

3. Java - Language Constructs I

Language Design COMS W4115. Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science

Introduction to C++ with content from

CMPE-013/L. Introduction to C Programming

CS Programming In C

Introduction to C Language

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

>B<82. 2Soft ware. C Language manual. Copyright COSMIC Software 1999, 2001 All rights reserved.

XSEDE Scholars Program Introduction to C Programming. John Lockman III June 7 th, 2012

Variables and literals

Tokens, Expressions and Control Structures

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Introduction to Programming Using Java (98-388)

Chapter 2 - Introduction to C Programming

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

Review of the C Programming Language

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

C Language, Token, Keywords, Constant, variable

Q1. Multiple Choice Questions

edunepal_info

Data Types and Variables in C language

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

MISRA-C:2012 Standards Model Summary for C / C++

Fundamental of Programming (C)

Programming in C. 4. Misc. Library Features, Gotchas, Hints and Tips. Dr. Neel Krishnaswami University of Cambridge

Programming in C++ 4. The lexical basis of C++

C++ Quick Guide. Advertisements

Types, Operators and Expressions

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

CSC 1107: Structured Programming

Crash Course into. Prof. Dr. Renato Pajarola

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

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

C - Basics, Bitwise Operator. Zhaoguo Wang

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

I BCA[ ] SEMESTER I CORE: C PROGRAMMING - 106A Multiple Choice Questions.

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

Types, Operators and Expressions

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

VARIABLES AND CONSTANTS

Introduction to Computing Lecture 01: Introduction to C

EL2310 Scientific Programming

Motor Industry Software Reliability Association (MISRA) C:2012 Standard Mapping of MISRA C:2012 items to Goanna checks

CS313D: ADVANCED PROGRAMMING LANGUAGE

Preview from Notesale.co.uk Page 6 of 52

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

BLM2031 Structured Programming. Zeyneb KURT

Transcription:

Programming in C and C++ 1. Types Variables Expressions & Statements Dr. Anil Madhavapeddy University of Cambridge (based on previous years thanks to Alan Mycroft, Alastair Beresford and Andrew Moore) Michaelmas Term 2015 2016 1 / 23

Structure of this course Programming in C: types, variables, expressions & statements functions, compilation, pre-processor pointers, structures extended examples, tick hints n tips Programming in C++: references, overloading, namespaces,c/c++ interaction operator overloading, streams, inheritance exceptions and templates standard template library Java native interface (JNI) 2 / 23

Text books There are literally hundreds of books written about C and C++; five you might find useful include: Eckel, B. (2000). Thinking in C++, Volume 1: Introduction to Standard C++ (2nd edition). Prentice-Hall. (http://www.mindview.net/books/ticpp/thinkingincpp2e.html) Kernighan, B.W. & Ritchie, D.M. (1988). The C programming language (2nd edition). Prentice-Hall. Stroustrup, B. (2000). The C++ Programming Language Special Edition (3rd edition). Addison Wesley Longman Stroustrup, B. (1994). The design and evolution of C++. Addison-Wesley. Lippman, S.B. (1996). Inside the C++ object model. Addison-Wesley. 3 / 23

Past Exam Questions 1993 Paper 5 Question 5 1993 Paper 6 Question 5 1994 Paper 5 Question 5 1994 Paper 6 Question 5 1995 Paper 5 Question 5 1995 Paper 6 Question 5 1996 Paper 5 Question 5 (except part (f) setjmp) 1996 Paper 6 Question 5 1997 Paper 5 Question 5 1997 Paper 6 Question 5 1998 Paper 6 Question 6 * 1999 Paper 5 Question 5 * (first two sections only) 2000 Paper 5 Question 5 * 2006 Paper 3 Question 4 * 2007 Paper 3 Question 4 2007 Paper 11 Question 3 2008 Paper 3 Question 3 2008 Paper 10 Question 4 2009 Paper 3 Question 1 2010 Paper 3 Question 6 2011 Paper 3 Question 3 * denotes CPL questions relevant to this course. 4 / 23

Context: from BCPL to Java 1966 Martin Richards developed BCPL 1969 Ken Thompson designed B 1972 Dennis Ritchie s C 1979 Bjarne Stroustrup created C with Classes 1983 C with Classes becomes C++ 1989 Original C90 ANSI C standard (ISO adoption 1990) 1990 James Gosling started Java (initially called Oak) 1998 ISO C++ standard 1999 C99 standard (ISO adoption 1999, ANSI, 2000) 2011 C++11 ISO standard (a.k.a. C++0x) 5 / 23

C is a low-level language C uses low-level features: characters, numbers & addresses Operators work on these fundamental types No C operators work on composite types e.g. strings, arrays, sets Only static definition and stack-based local variables heap-based storage is implemented as a library There are no read and write primitives instead, these are implemented by library routines There is only a single control-flow no threads, synchronisation or coroutines C seen as a high-level assembly language (take care!) 6 / 23

Classic first example 1 #include <stdio.h> 2 3 int main(void) 4 { 5 printf("hello, world\n"); 6 return 0; 7 } Compile with: $ cc example1.c Execute program with: $./a.out Hello, world $ Produce assembly code: $ cc -S example1.c 7 / 23

Basic types C has a small and limited set of basic types: type description (size) char characters ( 8 bits) int integer values ( 16 bits, commonly one word) float single-precision floating point number double double-precision floating point number Precise size of types is architecture dependent Various type operators for altering type meaning, including: unsigned, long, short, const, volatile This means we can have types such as long int and unsigned char C99 added fixed width types int16_t, uint64_t etc. as typedefs 8 / 23

Constants Numeric constants can be written in a number of ways: type style example char none none int number, character or escape 12 A \n \007 seq. long int number w/suffix l or L 1234L float number with., e or E 1.234e3F or 1234.0f and suffix f or F double number with., e or E 1.234e3 1234.0 long double number., e or E and suffix l or L 1.234E3l or 1234.0L Numbers can be expressed in octal by prefixing with a 0 and hexadecimal with 0x ; for example: 52=064=0x34 9 / 23

Defining constant values An enumeration can be used to specify a set of constants; e.g.: enum boolean {FALSE, TRUE}; By default enumerations allocate successive integer values from zero It is possible to assign values to constants; for example: enum months {JAN=1,FEB,MAR} enum boolean {F,T,FALSE=0,TRUE,N=0,Y} Names for constants in different enums must be distinct; values in the same enum need not The preprocessor can also be used (more on this later) 10 / 23

Variables Variables must be declared before use Variables must be defined (i.e. storage set aside) exactly once. (A definition counts as a declaration). A variable name can be composed of letters, digits and underscore (_); a name must begin with a letter or underscore Variables are defined by prefixing a name with a type, and can optionally be initialised; for example: long int i = 28L; Multiple variables of the same basic type can be declared or defined together; for example: char c,d,e; 11 / 23

Operators All operators (including assignment) return a result Most operators are similar to those found in Java: type operators arithmetic + - * / ++ -- % logic ==!= > >= < <= &&! bitwise & << >> ^ ~ assignment = += -= *= /= %= <<= >>= &= = ^= other sizeof 12 / 23

Type conversion Automatic type conversion may occur when two operands to a binary operator are of a different type Generally, conversion widens a variable (e.g. short int) However narrowing is possible and may not generate a compiler warning; for example: 1 int i = 1234; 2 char c; 3 c = i+1; /* i overflows c */ Type conversion can be forced by using a cast, which is written as: (type) exp; for example: c = (char) 1234L; 13 / 23

Expressions and statements An expression is created when one or more operators are combined; for example x *= y % z Every expression (even assignment) has a type and a result Operator precedence provides an unambiguous interpretation for every expression An expression (e.g. x=0) becomes a statement when followed by a semicolon (i.e. x=0;) Several expressions can be separated using a comma, ; expressions are then evaluated left to right; for example: x=0,y=1.0 The type and value of a comma-separated expression is the type and value of the result of the right-most expression 14 / 23

Blocks or compound statements A block or compound statement is formed when multiple statements are surrounded with braces ({ }) A block of statements is then equivalent to a single statement In ANSI/ISO C90, variables can only be declared or defined at the start of a block (this restriction was lifted in ANSI/ISO C99) Blocks are typically associated with a function definition or a control flow statement, but can be used anywhere 15 / 23

Variable scope Variables can be defined outside any function, in which case they: are often called global or static variables have global scope and can be used anywhere in the program consume storage for the entire run-time of the program are initialised to zero by default Variables defined within a block (e.g. function): are often called local or auto variables (register encourages the compiler to use a register rather than stack) can only be accessed from definition until the end of the block are only allocated storage for the duration of block execution are only initialised if given a value; otherwise their value is undefined 16 / 23

Variable definition versus declaration A variable can be declared but not defined using the extern keyword; for example extern int a; The declaration tells the compiler that storage has been allocated elsewhere (usually in another source file) If a variable is declared and used in a program, but not defined, this will result in a link error (more on this later and in the Compiler Construction course) 17 / 23

Scope and type example 1 #include <stdio.h> 2 3 int a; /*what value does a have? */ 4 unsigned char b = A ; 5 extern int alpha; /* safe to use this? */ 6 7 int main(void) { 8 extern unsigned char b; /* is this needed? */ 9 double a = 3.4; 10 { 11 extern a; /*why is this sloppy? */ 12 printf("%d %d\n",b,a+1); /*what will this print? */ 13 } 14 15 return 0; 16 } 18 / 23

Arrays and strings One or more items of the same type can be grouped into an array; for example: long int i[10]; The compiler will allocate a contiguous block of memory for the relevant number of values Array items are indexed from zero, and there is no bounds checking Strings in C are typically represented as an array of chars, terminated with a special character \0 There is language support for this representation of string constants using the " character; for example: char str[]="two strs mer" "ged and terminated" (note the implicit compile-time concatenation) String support is available in the string.h library 19 / 23

Control flow Control flow is similar to Java: exp? exp : exp if (exp) stmt 1 else stmt 2 switch(exp) { case exp 1 : stmt 1... default: stmt n+1 } while (exp) stmt for ( exp1 ; exp 2 ; exp 3 ) stmt do stmt while (exp); The jump statements break and continue also exist 20 / 23

Control flow and string example 1 #include <stdio.h> 2 #include <string.h> 3 4 char s[]="university of Cambridge Computer Laboratory"; 5 6 int main(void) { 7 8 char c; 9 int i, j; 10 for (i=0,j=strlen(s)-1;i<j;i++,j--) /* strlen(s)-1? */ 11 c=s[i], s[i]=s[j], s[j]=c; 12 13 printf("%s\n",s); 14 return 0; 15 } 21 / 23

Goto (considered harmful) The goto statement is never required It often results in code which is hard to understand and maintain Exception handling (where you wish to exit or break from two or more loops) may be one case where a goto is justified: 1 for (...) { 2 for (...) { 3... 4 if (critical_problem) 5 goto error; 6 } 7 } 8... 9 error: fix problem, or abort 22 / 23

Exercises 1. What is the difference between a and "a"? 2. Will char i,j; for(i=0; i<10,j!=5; i++,j++) ; terminate? If so, under what circumstances? 3. Write an implementation of bubble sort for a fixed array of integers. (An array of integers can be defined as int i[] = {1,2,3,4}; the 2nd integer in an array can be printed using printf("%d\n",i[1]);.) 4. Modify your answer to (3) to sort characters into lexicographical order. (The 2nd character in a character array i can be printed using printf("%c\n",i[1]);.) 23 / 23