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

Similar documents
QUIZ. Source:

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

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ. Can you find 5 errors in this code?

Ch. 10: Name Control

QUIZ Friends class Y;

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Ch. 11: References & the Copy-Constructor. - continued -

A Fast Review of C Essentials Part I

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

EL6483: Brief Overview of C Programming Language

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

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

Ch. 12: Operator Overloading

377 Student Guide to C++

III. Classes (Chap. 3)

Computer Science 306 Study Guide

BLM2031 Structured Programming. Zeyneb KURT

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

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

C++ for Java Programmers

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

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

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

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

CS3157: Advanced Programming. Outline

Final CSE 131B Spring 2004

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

CS24 Week 3 Lecture 1

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

CSE 374 Programming Concepts & Tools

CSE 303: Concepts and Tools for Software Development

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

Object-Oriented Programming, Iouliia Skliarova

Topic 6: A Quick Intro To C

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Ch. 3: The C in C++ - Continued -

Introduction to C++ with content from

CS3215. Outline: 1. Introduction 2. C++ language features 3. C++ program organization

Separate Compilation of Multi-File Programs

CS Programming In C

The Dynamic Typing Interlude

Chapter 19: Program Design. Chapter 19. Program Design. Copyright 2008 W. W. Norton & Company. All rights reserved.

Data Storage. August 9, Indiana University. Geoffrey Brown, Bryce Himebaugh 2015 August 9, / 19

Tokens, Expressions and Control Structures

Software Engineering /48

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

Programming, numerics and optimization

Midterm CSE 131B Spring 2005

C++ For Science and Engineering Lecture 15

CS61C : Machine Structures

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

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

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

CS61C : Machine Structures

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

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

QUIZ. How could we disable the automatic creation of copyconstructors

TDDE18 & 726G77. Functions

CS16 Week 2 Part 2. Kyle Dewey. Thursday, July 5, 12

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

Software Design and Analysis for Engineers

CSE 333 Midterm Exam 7/22/12

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

CMPE-013/L. Introduction to C Programming

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

QUIZ. How could we disable the automatic creation of copyconstructors

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

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

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Pointers and References

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

First of all, it is a variable, just like other variables you studied

Lesson 2 Variables and I/O

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Fast Introduction to Object Oriented Programming and C++

Creating a C++ Program

ECE 15B COMPUTER ORGANIZATION

The New C Standard (Excerpted material)

PROGRAMMAZIONE I A.A. 2017/2018

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

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

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Summer May 11, 2010

Chapter 1 Getting Started

CE221 Programming in C++ Part 1 Introduction

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

PIC 10A Objects/Classes

Operator overloading

Transcription:

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

Solution

QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c

Solution The C/C++ preprocessor substitutes mechanically, from top to bottom inside the file. On the left, the occurrences of i inside main are both replaced by 20, whereas on the right they are both replaced by 30. Note that the compiler sees and empty function fun in both cases!

QUIZ: Pointer to function What is wrong in this program?

Solution The compiler expects ptr to point to a specific type of function one with a char as the first argument. Instead, when ptr is used to access func, the first argument is an int! Note below that the C++ compiler is more strict than the C compiler (as expected):

Ch. 4: Data Abstraction

text The only way to get massive increases in productivity is to leverage off other people s code. That is, to use libraries. One of the primary design goals of C++ is to make library use easier.

QUIZ What abstract data types are available in C?

Solution The abstract types in C, are: arrays, structs, unions, enums.

Review of C structs: EoC problem #4 Named foo Named bar

Remember to employ using instead of typedef in C++ 11 and later! Solution

Solution

Solution

Solution

A tiny C-like library text Most C libraries have a set of structs and a set of functions that act on those structs. las an example, consider a programming tool that acts like an array, but whose size can be established at runtime, when it is created. li ll call it a CStash. lalthough it s written in C++, it has the style of what you d write in C:

currently allocated The index of the next empty element. It also means the number of elements currently stored. Note that every function takes a pointer to the struct as argument!

Explained on the next slides

What is assert.h (cassert in C++) used for? example

The actual message is implementation-dependent Note that cout wasn t executed assert caused the program to exit!

Implementation continued

QUIZ Why are structure arguments generally passed as pointers in C?

Why are structure arguments generally passed as pointers in C? If passed by value: A copy of the struct is made, wasting memory (think big structs!) Changes made by the function are not visible outside.

What does this mean? QUIZ

element is a pointer to void, i.e. to a yet-unknown piece of data. The function will find how many bytes the data has from the size field of s The data pointed to by element is constant, i.e. it cannot be changed (for safety)

Implementation continued

Implementation continued

To do for next time: Read and thoroughly understand the text section A Tiny C-like library

Remember from ch.2: separate compilation For each translation unit (.cpp file), the compiler creates an object file, with an extension of.o or.obj or something similar. These object files, along with the necessary start-up code, must be collected by the linker into the executable program (.exe). During linking, all the external references must be resolved.

Separate compilation For example, in CLibTest.cpp, functions such as initialize( ) and fetch( ) are declared (that is, the compiler is told what they look like) and used, but not defined. They are defined elsewhere, in CLib.cpp. Thus, the calls in CLib.cpp are external references. The linker must, when it puts all the object files together, take the unresolved external references and find the addresses they actually refer to. Those addresses are put into the executable program to replace the external references.

Problem: Name clash Labels in assembly language In C, the external references are simply function names, generally with an underscore in front of them. So all the linker has to do is match up the function name where it is called and the function body in the object file, and it s done. If you accidentally made a call that the compiler interpreted as func(int) and there s a function body for func(float) in some other object file, the linker will see _func in one place and _func in another, and it will think everything s OK.

How a name clash can lead to a bug The func( ) at the calling location will push an int onto the stack, and the func( ) function body will expect a float to be on the stack. If the function only reads the value and doesn t write to it, it won t blow up the stack. (In fact, the float value it reads off the stack might even make some kind of sense. That s worse because it s harder to find the bug. )

Manual name decoration To solve this problem, C library vendors will often prepend a sequence of unique characters to the beginning of all their function names. So initialize( ) and cleanup( ) might become CStash_initialize( ) and CStash_cleanup( ). This is a logical thing to do because it decorates the name of the struct the function works on with the name of the function, but it creates redundancy: void CStash_cleanup(CStash *s);

A better solution! [ ] the first step toward creating classes in C++. Variable names inside a struct do not clash with global variable names. So why not take advantage of this for function names, when those functions operate on a particular struct? That is, why not make functions members of structs?

In a C program (extension.c), we cannot have functions as members of a struct however, in a C++ program (extension.cpp), functions members are OK!

No typedef needed this is already a type!

Decoration is done with the scope resolution operator Not S -> size No more Stash *s as first argument!

QUIZ Named Foo Named bar EOL 1

QUIZ: C libraries What is the typical structure of a C library?

Most C libraries have a set of structs and a set of functions that act on those structs. The first argument of such a function is usually a struct pointer.

QUIZ What are two differences between structs in C and C++?

What are two differences between structs in C and C++? C++ structs may contain function members (a.k.a. methods) The tag of a C++ struct is a name by itself we don t precede it with struct when declaring objects (and no need for typedef!)

QUIZ Declare a struct named Aaa with the following members: Float member f Integer member p Function member power that returns the number f p (declaration and definition) Create, initialize and use and object a of type Aaa in the main program.

solution

solution

solution

Stronger type checking in C++ While C++ allows the assignment of any type of pointer to a void* (this was the original intent of void*, which is required to be large enough to hold a pointer to any type), it will not allow you to assign a void pointer to any other type of pointer. A cast is always required to tell the reader and the compiler that you really do want to treat it as the destination type.

QUIZ Use a typecast in the last line to make it legal in C++: C-style typecast C++-style typecast

OOP lingo: object

Abstract data typing The definition of Stash creates a new data type. You create one by saying Stash s, just as you create a float by saying float f. A Stash also has characteristics and behavior. Even though it acts like a real, built-in data type, we refer to it as an abstract data type (ADT), perhaps because it allows us to abstract a concept from the problem space into the solution space. ADTs are sometimes called user-defined types.

Abstract data typing The C++ compiler treats an abstract type like any data type. E.g. if you say a function expects a Stash, the compiler makes sure you pass a Stash to that function. The same level of type checking happens with abstract data types as with built-in types.

You can immediately see a difference, however, in the way you perform operations on objects. You say object.memberfunction(arglist). This is calling a member function for an object. But in object-oriented parlance, this is also referred to as sending a message to an object. So for a Stash s, the statement s.add(&i) sends a message to s saying, add( ) this to yourself.

OOP can be summed up in a single phrase: sending messages to objects. The trick, of course, is figuring out what your objects and messages are, but once you accomplish this the implementation in C++ is surprisingly straightforward.

Object details A question that often comes up in seminars is, How big is an object, and what does it look like? The answer is about what you expect from a C struct. In fact, the code the C compiler produces for a C struct (with no C++ adornments) will usually look exactly the same as the code produced by a C++ compiler.

Object details The size of a struct is the combined size of all of its members. Sometimes when the compiler lays out a struct, it adds extra bytes to make the boundaries come out neatly this may increase execution efficiency.

We can determine the size of a struct using the sizeof operator:

Header file etiquette Why do we need header files? text When you create a struct containing member functions, you are creating a new data type. In general, you want this type to be easily accessible to yourself and others. In addition, you want to separate the interface (the declaration) from the implementation (the definition of the member functions) so the implementation can be changed without forcing a re-compile of the entire system. You achieve this end by putting the declaration for your new type in a header file.

Three rules for header files 1. What can we put into header files? The basic rule is only declarations, i.e. nothing that allocates storage by generating code or creating variables. This is because the header file will typically be included in several translation units in a project, and if storage for one identifier is allocated in more than one place, the linker will come up with a multiple definition error (this is C++ s one definition rule: You can declare things as many times as you want, but there can be only one actual definition for each thing).

Three rules for header files 2. How are multiple declarations handled? It is possible for the.h file to be included more than once in a complicated program. Both C and C++ allow you to redeclare a function, as long as the two declarations match, but neither will allow the redeclaration of a structure.

2. How are multiple declarations handled? The compiler considers the redeclaration of a structure (this includes both structs and classes) to be an error, since it would otherwise allow you to use the same name for different types. To prevent this error when multiple header files are included, you need to build some intelligence into your header files using the preprocessor (Standard C++ header files like <iostream> already have this intelligence ).

The preprocessor directives #define, #ifdef, and #endif The name HEADER_FLAG can be any unique name, but a reliable standard to follow is to capitalize the name of the header file and replace periods with underscores (leading underscores, however, are reserved for system names). Here s an example:

These preprocessor statements that prevent multiple inclusion are often referred to as include guards.

3. How are using directives handled? The using directive eliminates the protection of that particular namespace, and the effect lasts until the end of the current compilation unit. If you put a using directive (outside of a scope) in a header file, it means that this loss of namespace protection will occur with any file that includes this header, which often means other header files. It s very easy to end up turning off namespaces practically everywhere, and thereby neutralizing the beneficial effects of namespaces.

3. How are using directives handled? Do not put using in header files!

Nested structures Both C and C++ allow declaration of a struct inside another. Here is a simple example (not in text): http://www.c4learn.com/c-programming/c-nested-structure/

Nested structure example? Draw memory diagram! Note that there are two functions initialize! http://www.c4learn.com/c-programming/c-nested-structure/

Nested structure example http://www.c4learn.com/c-programming/c-nested-structure/

Read and understand the full implementation and test files for the stack

Global scope resolution The scope resolution operator gets you out of situations in which the name the compiler chooses by default (the nearest name) isn t what you want. For example, suppose you have a structure with a local identifier a, and you want to select a global identifier a from inside a member function. The compiler would default to choosing the local one, so you must tell it to do otherwise.

QUIZ What does this program output?

QUIZ What does this program output?

QUIZ What does this program output?

QUIZ What does this program output?

No homework assigned yet for ch. 4 EOL 2