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

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

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

Ch. 10: Name Control

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?

QUIZ. Source:

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

Object-Oriented Programming, Iouliia Skliarova

C++ for Java Programmers

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

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

QUIZ Friends class Y;

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors

Fast Introduction to Object Oriented Programming and C++

Introduction to C++ with content from

Ch. 12: Operator Overloading

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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?

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

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

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

Lecture Topics. Administrivia

A Fast Review of C Essentials Part I

Pointers and References

Review of the C Programming Language for Principles of Operating Systems

BLM2031 Structured Programming. Zeyneb KURT

Review of the C Programming Language

Tokens, Expressions and Control Structures

CSE 374 Programming Concepts & Tools

Variables. Data Types.

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

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Software Design and Analysis for Engineers

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

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

377 Student Guide to C++

Programming in C and C++

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

VARIABLES AND TYPES CITS1001

Intro. Scheme Basics. scm> 5 5. scm>

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Instantiation of Template class

Expressions and Casting

EL6483: Brief Overview of C Programming Language

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Software Design and Analysis for Engineers

C Language Programming

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

Chapter 1 Getting Started

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

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Variables and literals

We do not teach programming

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

CSE 303: Concepts and Tools for Software Development

The Dynamic Typing Interlude

G52CPP C++ Programming Lecture 9

Interview Questions of C++

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

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

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013


6.096 Introduction to C++ January (IAP) 2009

Constants, References

Pointers, Dynamic Data, and Reference Types


CS201 Some Important Definitions

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Important From Last Time

Page 1. Today. Important From Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right?

A brief introduction to C++

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

A brief introduction to C programming for Java programmers

Object-Oriented Programming for Scientific Computing

Fundamental Concepts and Definitions

Copyie Elesion from the C++11 mass. 9 Sep 2016 Pete Williamson

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

M.EC201 Programming language

CS61C : Machine Structures

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

CS

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

Memory, Arrays & Pointers

1: Introduction to Object (1)

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

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

1.7 Limit of a Function

Chapter 13: Copy Control. Overview. Overview. Overview

Lecture 2, September 4

Transcription:

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

Solution The value of the default argument should be placed in either declaration or definition, not both!

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

Solution Non-trailing default arguments are illegal.

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

Solution Nothing is wrong, it compiles and runs fine

Ch. 8: Constants Note: Review the section on constants from ch.3!

BUFSIZE is a name that only exists during preprocessing, therefore it doesn t occupy storage and can be placed in a header file to provide a single value for all translation units that use it. Most of the time, BUFSIZE will behave like an ordinary variable, but not all the time. In addition, there s no type information. This can hide bugs that are very difficult to find. Because of subtle bugs that the preprocessor might introduce, you should always use const instead of #define value substitution in C++.

C++ uses const to eliminate these problems by bringing value substitution into the domain of the compiler: You can use bufsize anyplace where the compiler must know the value at compile time. The compiler can use bufsize to perform constant folding, which means the compiler will reduce a complicated constant expression to a simple one by performing the necessary calculations at compile time.

QUIZ Will any multiplications be performed at run-time in this program?

Will any multiplications be performed at run-time in this program? A: No, the compiler applies constant folding.

Important difference from C:

const in header files A const in C++ defaults to internal linkage; that is, it is visible only within the file where it is defined and cannot be seen at link time by other translation units. You must always assign a value to a const when you define it, except when you make an explicit declaration using extern:

Normally, the C++ compiler avoids creating storage for a const, but instead holds the definition in its symbol table. When you use extern with const, however, you force storage to be allocated. This is also true for certain other cases, such as: taking the address of a const complicated structs. With built-in types, which are used in the majority of cases involving constant expressions, the compiler can always perform constant folding.

Safety consts The use of const is not limited to replacing #defines at compile time. If you initialize a variable with a value that is produced at runtime and you know it will not change for the lifetime of that variable, it is good programming practice to make it a const so the compiler will give you an error message if you accidentally try to change it. example

Compile-time constants Run-time constants

Aggregates It s possible to use const for aggregates, but you re virtually assured that the compiler will not be sophisticated enough to keep an aggregate in its symbol table, so storage will be allocated. In these situations, const means a piece of storage that cannot be changed. However, the value cannot be used at compile time [for constant folding] b/c the compiler is not required to know the contents of the storage at compile time. example

QUIZ Which statements are illegal?

Solution Which statements are illegal?

Read the subsection Differences with C

Pointers can be made const. Pointers The compiler will still endeavor to prevent storage allocation and do constant folding when dealing with const pointers, but these features seem less useful in this case. More importantly, the compiler will tell you if you attempt to change a const pointer, which adds a great deal of safety.

When using const with pointers, there are two options: const can be applied to what the pointer is pointing to const can be applied to the address stored in the pointer itself. Image source: http://webforce.blogspot.com/

Pointer to const vs. const pointer Compiler rule: const binds to the identifier closest to itself int * u; examples

Compiler rule: const binds to the identifier closest to itself Data is constant. Legal, but not recommended. Data is constant. const int * u; int const * u; int * u; Address is constant. int * const u; int * u const; Illegal

When the address is constant, it has to be initialized when it is declared (Why?) int a = 42, b = 100; int * const u = &a;

QUIZ Describe each pointer:

QUIZ Which statements are illegal?

Solution Which statements are illegal?

Formatting int* u; or int *u;? It only matters when we declare multiple pointers in one statement The * is actually attached to the name of the pointer: int *u, *v, *w;

Assignment and type checking C++ is very particular about type checking, and this extends to pointer assignments.

Assignment and type checking You can assign the address of a non-const object to a const pointer because you re simply promising not to change something that is OK to change.

However, you can t assign the address of a const object to a nonconst pointer because then you re saying you might change the object via the pointer. You can use a cast to force such an assignment, but this is bad programming practice b/c you are then breaking the constness of the object, along with any safety promised by the const.

We stop before the section Returning by const value Individual work for next time: End-of-chapter 1, 2, 4. EOL 1

QUIZ Where does constant folding fail in this example? Explain!

Solution Where does constant folding fail in this example? Explain!

Follow-up Interestingly, if the aggregate is inside a function scope, the program compiles and runs OK: Not recommended!

QUIZ Which constants are run-time and which compile-time in this program?

Solution Compile-time constants Run-time constants

QUIZ Will this program compile correctly?

Solution Will this program compile correctly?

QUIZ Will this program compile correctly? Can we force it (if we really wanted to)?

Solution Yes, through typecasting: but it s not recommended! Just find a better code design

Extra-credit:

The problem of character array literals C.A.L. are arrays with constant data, so the correct declaration should be

The compiler lets you get away with treating them as nonconst because there s so much existing C code that relies on this but this works only in the declaration line! Fix:

If you want to be able to modify the string, put it in an array: Output

Function arguments & return values

QUIZ Do the same with a pointer

Solution

A const return value can only make a difference when the function call is an lvalue, i.e. it appears on the left-hand side of an assignment! example

In C we re never allowed to use the returned object as an lvalue! In C++: When the return type is one of the built-ins, this is the end of the story, since we re not allowed to use the returned object as lvalue: However, when the returned object is user-defined or a reference, in C++ it is allowed to use it as lvalue: example

In C++, return value can be used as lvalue, but only if it s user-defined Non-const built-in value Non-const user-defined value Quite useless, isn t it? But see the next slide Not in text

or a reference! Non-const reference! Non-const reference! Now the returned object is changed! Not in text

Quote from The Design and Evolution of C++ [by Bjarne Stroustrup]: [ ] ideal for the design of C++: User-defined and built-in types should behave the same relative to the language rules and receive the same degree of support from the language and its associated tools. When the ideal was formulated built-in types received by far the best support, but C++ has overshot that target so that built-in types now receive slightly inferior support compared to user-defined types. Source: https://stackoverflow.com/questions/6111905/c-is-return-value-a-l-value Not in text

but we can prevent this by using const Const reference!

Remember from C that structs can be assigned to each other (unlike arrays)!

But, wait a second, what use could this be? Why does C++ even allow to use the returned object as lvalue?

For a concrete example, consider std::cout << "Hello, world" << std::endl; The first operator<< () returns an lvalue on which you can call the second operator<< (). So this practice of calling methods on return values is more common than many people would think. MSalters Source: https://stackoverflow.com/questions/6111905/c-is-return-value-a-l-value Not in text

Temporaries Sometimes, during the evaluation of an expression, the compiler must create temporary objects. These are objects like any other: they require storage and they must be constructed and destroyed [ ] They re automatically const. Because you usually won t be able to get your hands on a temporary object, telling it to do something that will change that temporary is almost certainly a mistake because you won t be able to use that information. By making all temporaries automatically const, the compiler informs you when you make that mistake. example

Simplified example with temporary (temporaries are created for built-in data types, too!) The class X from C08:ConstReturnValues.cpp is replaced here by int. The compiler creates a temporary object to hold the return value of f5( ) so it can be passed to f7( )

Passing and returning addresses pointers and references Rule of thumb: Unless we have a reason to do otherwise, both passing and returning should be done by: Constant reference, or Pointer to constant OK, I get this, but which one should I use, pointer or reference? Answer follows

Passing and returning addresses Rule of thumb: pointers and references Use reference unless the value passed or returned : can be NULL, or points to a block of dynamically allocated memory whose ownership is thereby transferred (we cannot delete references, only pointers)

Passing and returning addresses pointers and references Read and understand: C08:ConstPointer.cpp C08:ConstTemporary.cpp

Advantages of passing arguments by const reference To the client programmers, the syntax is identical to that of passing by value, so there s no confusion about pointers they don t even have to think about pointers. For the creator of the function, passing an address is virtually always more efficient than passing an entire class object If you pass by const reference it means your function will not change the destination of that address, so the effect from the client programmer s point of view is exactly the same as pass-by-value. EOL 2

QUIZ What is an lvalue?

QUIZ Compare C and C++: Is is possible to use the value returned by a function as an lvalue?

Solution Compare C and C++: Is is possible to use the value returned by a function as an lvalue? Built-in data types (int, char, float, etc.) and any pointers User-defined data types (struct, class, union) and any references C No No C++ No Yes

QUIZ What is a temporary?

text Solution What is a temporary? Sometimes, during the evaluation of an expression, the compiler must create temporary objects. These are objects like any other: they require storage and they must be constructed and destroyed. The difference is that you never see them the compiler is responsible for deciding that they re needed and the details of their existence. Example: f7(f5()); the compiler must manufacture a temporary object to hold the return value of f5( ) so it can be passed to f7( ).

QUIZ Are temporaries const or non-const? Explain why.

text Solution Are temporaries const or non-const? Explain why. [ ] temporaries [are] automatically const. Because you usually won t be able to get your hands on a temporary object, telling it to do something that will change that temporary is almost certainly a mistake because you won t be able to use that information. By making all temporaries automatically const, the compiler informs you when you make that mistake.

Using const with classes One of the places you d like to use a const for constant expressions is inside classes. Typical example: creating an array inside a class. We want to use a const instead of a #define to establish the array size The array size is something we d like to keep hidden inside the class, so if we used a name like size, we could use that name in another class without a clash. (The preprocessor treats all #defines as global!)

Problem: Different objects of this class should be allowed to have different array sizes! Thus, when we create an ordinary (non-static) const inside a class, we cannot give it an initial value. This initialization must occur in the constructor, so each object instantiated can have its own value for the const. but it cannot be as normal, executable code, because this would contradict its constness!

Solution: Inside the constructor, there is a special initialization point, called the constructor initializer list. It is a list of constructor calls that occur after the function argument list, but before the opening brace of the constructor body. example

constructor initializer list This particular constructor has no executable body size is of type int, so it seems that we re using a constructor for a built-in type!

Extra-credit

In the constructor initializer list, we can treat a built-in type as if it had a constructor.

In the constructor initializer list, we can treat a built-in type as if it has a constructor. This rule was extended to non-const data members! (But it is the only option for const data members!)

Practice: Instantiate an object of this class in the main program.

In the constructor initializer list, we can treat a built-in type as if it has a constructor. This rule was also extended (for consistency) to all built-in types: but be careful: Source: http://stackoverflow.com/questions/5113365/do-built-in-types-have-default-constructors

Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of how many objects of the class are created User-defined types will be addressed soon! A static const of a built-in type can be treated as a compile-time constant. static consts must be initialized when they are defined (all other data members must be initialized in the constructor or in other member functions) example

Initialized at the point of definition!

QUIZ Draw a memory diagram for a StringStack object.

solution

The enum hack in old code No tag! Like in C, we can tell the compiler what integer we want.

QUIZ Run-time or compile-time constant? Why is it not possible to initialize size inside the body of the constructor? What is this called?

QUIZ How can we make it a run-time constant? What else would change in the program?

const member functions Since f( ) is a const member function, if it attempts to change i in any way or to call another member function that is not const, the compiler flags it as an error.

const member functions Note the position of the const specifier: after the argument list, in both declaration and definition.

Practice: Create a class Foo with one const and one non-const member function named f_con and f_non_con. Both functions return void, have no arguments, and their bodies are empty. Create: one const object of type Foo named f1 one non-const objects of type Foo named f2 Try calling both member functions for each object; which calls are legal?

solution

solution

solution

solution

const objects If an object of a class is declared const, then it is only legal to call const member functions of that class with the object. example

The compiler does not look inside the function!

Read and the code example C08:Quoter.cpp and the text explanations. SKIP the subsections mutable: bitwise vs. logical const ROMability

volatile volatile means This data may change outside the knowledge of the compiler. Somehow, the environment is changing the data (possibly through multitasking, multithreading or interrupts), and volatile tells the compiler not to make any assumptions about that data, especially during optimization.

volatile The syntax of volatile is identical to that of const, so the two are often treated together. The two are referred to in combination as the c-v qualifier. You can also create const volatile objects, which can t be changed by the client programmer but instead change through some outside agency.

Read the code example C08:Volatile.cpp and the text explanations.

No homework is assigned now for ch.8. One will be assigned for chs. 8 and 9 together. EOL 3