Chapter 8
Chapter 8
Technicalities: Functions, etc.
Technicalities: Functions, etc.
Bjarne Stroustrup
www.stroustrup.com/Programming
Abstract
Abstract
 This lecture and the following present some technical
This lecture and the following present some technical
details of the language to give a slightly broader view
details of the language to give a slightly broader view
of C++’s basic facilities and to provide a more
of C++’s basic facilities and to provide a more
systematic view of those facilities. This also acts as a
systematic view of those facilities. This also acts as a
review of many of the notions presented so far, such
review of many of the notions presented so far, such
as types, functions, and initialization, and provides an
as types, functions, and initialization, and provides an
opportunity to explore our tool without adding new
opportunity to explore our tool without adding new
programming techniques or concepts.
programming techniques or concepts.
2
2
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Overview
Overview
 Language Technicalities
Language Technicalities
 Declarations
Declarations
 Definitions
Definitions
 Headers and the preprocessor
Headers and the preprocessor
 Scope
Scope
 Functions
Functions
 Declarations and definitions
Declarations and definitions
 Arguments
Arguments
 Call by value, reference, and
Call by value, reference, and const
const reference
reference
 Namespaces
Namespaces
 “
“Using” declarations
Using” declarations
3
3
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Language technicalities
Language technicalities
 Are a necessary evil
Are a necessary evil
 A programming language is a foreign language
A programming language is a foreign language
 When learning a foreign language, you have to look at the grammar and
When learning a foreign language, you have to look at the grammar and
vocabulary
vocabulary
 We will do this in this chapter and the next
We will do this in this chapter and the next
 Because:
Because:
 Programs must be precisely and completely specified
Programs must be precisely and completely specified
 A computer is a very stupid (though very fast) machine
A computer is a very stupid (though very fast) machine
 A computer can
A computer can’t guess what you “really meant to say” (and shouldn’t try to)
’t guess what you “really meant to say” (and shouldn’t try to)
 So we must know the rules
So we must know the rules
 Some of them (the C++14 standard is 1,358 pages)
Some of them (the C++14 standard is 1,358 pages)
 However, never forget that
However, never forget that
 What we study is programming
What we study is programming
 Our output is programs/systems
Our output is programs/systems
 A programming language is only a tool
A programming language is only a tool
4
4
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Technicalities
Technicalities
 Don’t spend your time on minor syntax and semantic issues.
Don’t spend your time on minor syntax and semantic issues.
There is more than one way to say everything
There is more than one way to say everything
 Just like in English
Just like in English
 Most design and programming concepts are universal, or at
Most design and programming concepts are universal, or at
least very widely supported by popular programming languages
least very widely supported by popular programming languages
 So what you learn using C++ you can use with many other languages
So what you learn using C++ you can use with many other languages
 Language technicalities are specific to a given language
Language technicalities are specific to a given language
 But many of the technicalities from C++ presented here have obvious
But many of the technicalities from C++ presented here have obvious
counterparts in C, Java, C#, etc.
counterparts in C, Java, C#, etc.
5
5
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Declarations
Declarations
 A declaration introduces a name into a scope.
A declaration introduces a name into a scope.
 A declaration also specifies a type for the named object.
A declaration also specifies a type for the named object.
 Sometimes a declaration includes an initializer.
Sometimes a declaration includes an initializer.
 A name must be declared before it can be used in a C++ program.
A name must be declared before it can be used in a C++ program.
 Examples:
Examples:
 int a = 7;
int a = 7; //
// an int variable named
an int variable named ‘a’ is declared
‘a’ is declared
 const double cd = 8.7;
const double cd = 8.7; //
// a double-precision floating-point constant
a double-precision floating-point constant
 double sqrt(double);
double sqrt(double); //
// a function taking a double argument and
a function taking a double argument and
//
// returning a double result
returning a double result

vector<Token> v;
vector<Token> v; //
// a vector variable of
a vector variable of Token
Tokens (variable)
s (variable)
6
6
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Declarations
Declarations
 Declarations are frequently introduced into a program through
Declarations are frequently introduced into a program through
“headers”
“headers”
 A header is a file containing declarations providing an interface to other
A header is a file containing declarations providing an interface to other
parts of a program
parts of a program
 This allows for abstraction – you don
This allows for abstraction – you don’
’t have to know the details
t have to know the details
of a function like
of a function like cout
cout in order to use it. When you add
in order to use it. When you add
#include "std_lib_facilities.h"
#include "std_lib_facilities.h"
to your code, the declarations in the file
to your code, the declarations in the file std_lib_facilities.h
std_lib_facilities.h
become available (including
become available (including cout
cout,
, etc.).
etc.).
7
7
Stroustrup/Programming/2015
Stroustrup/Programming/2015
For example
For example
 At least three errors:
At least three errors:
int main()
{
cout << f(i) << ′n′;
}
 Add declarations:
Add declarations:
#include ″std_lib_facilities.h″ // we find the declaration of cout in here
int main()
{
cout << f(i) << ′n′;
}
Stroustrup/Programming/2015
Stroustrup/Programming/2015 8
8
For example
For example
 Define your own functions and variables:
Define your own functions and variables:
#include ″std_lib_facilities.h″ // we find the declaration of cout in
here
int f(int x ) { /* … */ } // declaration of f
int main()
{
int i = 7; // declaration of i
cout << f(i) << ′n′;
}
Stroustrup/Programming/2015
Stroustrup/Programming/2015 9
9
Definitions
Definitions
A declaration that (also) fully specifies the entity declared is
A declaration that (also) fully specifies the entity declared is
called a definition
called a definition
 Examples
Examples
int a = 7;
int a = 7;
int b;
int b; //
// an (uninitialized) int
an (uninitialized) int
vector<double> v;
vector<double> v; //
// an empty vector of doubles
an empty vector of doubles
double sqrt(double) { … }; //
double sqrt(double) { … }; // a function with a body
a function with a body
struct Point { int x; int y; };
struct Point { int x; int y; };
 Examples of declarations that are not definitions
Examples of declarations that are not definitions
double sqrt(double);
double sqrt(double); //
// function body missing
function body missing
struct Point;
struct Point; //
// class members specified elsewhere
class members specified elsewhere
extern int a;
extern int a; //
// extern
extern means
means “not definition”
“not definition”
//
// “extern” is archaic; we will hardly use it
“extern” is archaic; we will hardly use it
10
10
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Declarations and definitions
Declarations and definitions
 You can’t
You can’t define
define something twice
something twice
 A definition says what something is
A definition says what something is
 Examples
Examples
int a;
int a; //
// definition
definition
int a;
int a; //
// error: double definition
error: double definition
double sqrt(double d) { … }
double sqrt(double d) { … } //
// definition
definition
double sqrt(double d) { … }
double sqrt(double d) { … } //
// error: double definition
error: double definition
 You can
You can declare
declare something twice
something twice
 A declaration says how something can be used
A declaration says how something can be used
int a = 7;
int a = 7; //
// definition (also a declaration)
definition (also a declaration)
extern int a;
extern int a; //
// declaration
declaration
double sqrt(double);
double sqrt(double); //
// declaration
declaration
double sqrt(double d) { … }
double sqrt(double d) { … } //
// definition (also a declaration)
definition (also a declaration)
11
11
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Why both declarations and
Why both declarations and
definitions?
definitions?
 To refer to something, we need (only) its declaration
To refer to something, we need (only) its declaration
 Often we want the definition “elsewhere”
Often we want the definition “elsewhere”
 Later in a file
Later in a file
 In another file
In another file
 preferably written by someone else
preferably written by someone else
 Declarations are used to specify interfaces
Declarations are used to specify interfaces
 To your own code
To your own code
 To libraries
To libraries
 Libraries are key: we can
Libraries are key: we can’t write all ourselves, and wouldn’t want to
’t write all ourselves, and wouldn’t want to
 In larger programs
In larger programs
 Place all declarations in header files to ease sharing
Place all declarations in header files to ease sharing
12
12
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Kinds of declarations
 The most interesting are
 Variables
 int x;
 vector<int> vi2 {1,2,3,4};
 Constants
 void f(const X&);
 constexpr int = isqrt(2);
 Functions (see §8.5)
 double sqrt(double d) { /* … */ }
 Namespaces (see §8.7)
 Types (classes and enumerations; see Chapter 9)
 Templates (see Chapter 19)
Stroustrup/Programming/2015
Stroustrup/Programming/2015 13
13
Header Files and the Preprocessor
Header Files and the Preprocessor
 A header is a file that holds declarations of functions, types,
A header is a file that holds declarations of functions, types,
constants, and other program components.
constants, and other program components.
 The construct
The construct
#include
#include "std_lib_facilities.h"
"std_lib_facilities.h"
is a
is a “
“preprocessor directive
preprocessor directive”
” that adds
that adds declarations to your
declarations to your
program
program
 Typically, the header file is simply a text (source code) file
Typically, the header file is simply a text (source code) file
 A header gives you access to functions, types, etc. that you
A header gives you access to functions, types, etc. that you
want to use in your programs.
want to use in your programs.
 Usually, you don
Usually, you don’t really care about how they are written.
’t really care about how they are written.
 The actual functions, types, etc. are defined in other source code files
The actual functions, types, etc. are defined in other source code files
 Often as part of libraries
Often as part of libraries
14
14
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Source files
Source files
 A header file (here,
A header file (here, token.h
token.h) defines an interface between user code
) defines an interface between user code
and implementation code (usually in a library)
and implementation code (usually in a library)
 The same
The same #include
#include declarations in both
declarations in both .cpp
.cpp files (definitions and
files (definitions and
uses) ease consistency checking
uses) ease consistency checking
15
15
// declarations:
class Token { … };
class Token_stream {
Token get();
…
};
extern Token_stream ts;
…
#include "token.h"
//definitions:
Token Token_stream::get()
{ /* … */ }
Token_stream ts;
…
#include "token.h"
…
Token t = ts.get();
…
token.h:
token.cpp:
use.cpp:
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Scope
Scope
 A scope is a region of program text
A scope is a region of program text
 Global scope (outside any language construct)
Global scope (outside any language construct)
 Class scope (within a class)
Class scope (within a class)
 Local scope (between { … } braces)
Local scope (between { … } braces)
 Statement scope (e.g. in a for-statement)
Statement scope (e.g. in a for-statement)
 A name in a scope can be seen from within its scope and within
A name in a scope can be seen from within its scope and within
scopes nested within that scope
scopes nested within that scope
 Only after the declaration of the name (
Only after the declaration of the name (“can’t look ahead” rule)
“can’t look ahead” rule)
 Class members can be used within the class before they are declared
Class members can be used within the class before they are declared
 A scope keeps “things” local
A scope keeps “things” local
 Prevents my variables, functions, etc., from interfering with yours
Prevents my variables, functions, etc., from interfering with yours
 Remember: real programs have
Remember: real programs have many
many thousands of entities
thousands of entities
 Locality is good!
Locality is good!
 Keep names as local as possible
Keep names as local as possible
16
16
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Scope
Scope
#include "std_lib_facilities.h"
#include "std_lib_facilities.h" //
// get
get max
max and
and abs
abs from here
from here
//
// no
no r, i,
r, i, or
or v
v here
here
class My_vector {
class My_vector {
vector<int> v;
vector<int> v; //
// v
v is in class scope
is in class scope
public:
public:
int largest()
int largest() //
// largest
largest is in class scope
is in class scope
{
{
int r = 0;
int r = 0; //
// r
r is local
is local
for (int i = 0; i<v.size(); ++i)
for (int i = 0; i<v.size(); ++i) //
// i
i is in statement scope
is in statement scope
r = max(r,abs(v[i]));
r = max(r,abs(v[i]));
//
// no
no i
i here
here
return r;
return r;
}
}
//
// no
no r
r here
here
};
};
//
// no
no v
v here
here
17
17
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Scopes nest
Scopes nest
int x;
int x; //
// global variable – avoid those where you can
global variable – avoid those where you can
int y;
int y; //
// another global variable
another global variable
int f()
int f()
{
{
int x;
int x; //
// local variable (Note – now there are two
local variable (Note – now there are two x
x’s)
’s)
x = 7;
x = 7; //
// local
local x
x, not the global
, not the global x
x
{
{
int x = y;
int x = y; //
// another local
another local x
x, initialized by the global
, initialized by the global y
y
//
// (Now there are three
(Now there are three x
x’s)
’s)
++x;
++x; //
// increment the local
increment the local x
x in this scope
in this scope
}
}
}
}
//
// avoid such complicated nesting and hiding: keep it simple!
avoid such complicated nesting and hiding: keep it simple!
18
18
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Recap: Why functions?
Recap: Why functions?
 Chop a program into manageable pieces
Chop a program into manageable pieces
 “
“divide and conquer”
divide and conquer”
 Match our understanding of the problem domain
Match our understanding of the problem domain
 Name logical operations
Name logical operations
 A function should do one thing well
A function should do one thing well
 Functions make the program easier to read
Functions make the program easier to read
 A function can be useful in many places in a program
A function can be useful in many places in a program
 Ease testing, distribution of labor, and maintenance
Ease testing, distribution of labor, and maintenance
 Keep functions small
Keep functions small
 Easier to understand, specify, and debug
Easier to understand, specify, and debug
Stroustrup/Programming/2015
Stroustrup/Programming/2015 19
19
Functions
Functions
 General form:
General form:
 return_type
return_type name
name (
(formal arguments
formal arguments);
); //
// a
a declaration
declaration
 return_type
return_type name
name (
(formal arguments
formal arguments)
) body
body //
// a
a
definition
definition
 For example
For example
double f(int a, double d) { return a*d; }
double f(int a, double d) { return a*d; }
 Formal arguments are often called parameters
Formal arguments are often called parameters
 If you don’t want to return a value give
If you don’t want to return a value give void
void as the return type
as the return type
void increase_power_to(int level);
void increase_power_to(int level);
 Here,
Here, void
void means
means “doesn’t return a value”
“doesn’t return a value”
 A body is a block or a try block
A body is a block or a try block
 For example
For example
{ /*
{ /* code
code */ }
*/ } //
// a block
a block
try { /*
try { /* code
code */ } catch(exception& e) { /*
*/ } catch(exception& e) { /* code
code */ }
*/ } //
// a try block
a try block
 Functions represent/implement computations/calculations
Functions represent/implement computations/calculations
20
20
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Functions: Call by Value
Functions: Call by Value
//
// call-by-value (send the function a copy of the argument’s value)
call-by-value (send the function a copy of the argument’s value)
int f(int a) { a = a+1; return a; }
int f(int a) { a = a+1; return a; }
int main()
int main()
{
{
int xx = 0;
int xx = 0;
cout << f(xx) <<
cout << f(xx) << ′n′;
; //
// writes
writes 1
1
cout << xx <<
cout << xx << ′n′;
; //
// writes
writes 0; f()
0; f() doesn’t change
doesn’t change xx
xx
int yy = 7;
int yy = 7;
cout << f(yy) <<
cout << f(yy) << ′n′; //
; // writes
writes 8; f()
8; f() doesn’t change
doesn’t change yy
yy
cout << yy <<
cout << yy << ′n′;
; //
// writes
writes 7
7
}
}
21
21
0
a:
xx:
copy the value
0
7
a:
yy:
copy the value
7
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Functions: Call by Reference
Functions: Call by Reference
//
// call-by-reference (pass a reference to the argument)
call-by-reference (pass a reference to the argument)
int f(int& a) { a = a+1; return a; }
int f(int& a) { a = a+1; return a; }
int main()
int main()
{
{
int xx = 0;
int xx = 0;
cout << f(xx) <<
cout << f(xx) << ′n′;
; //
// writes
writes 1
1
//
// f()
f() changed the value of
changed the value of xx
xx
cout << xx <<
cout << xx << ′n′;
; //
// writes
writes 1
1
int yy = 7;
int yy = 7;
cout << f(yy) <<
cout << f(yy) << ′n′; //
; // writes
writes 8
8
//
// f()
f() changes the value of
changes the value of yy
yy
cout << yy <<
cout << yy << ′n′;
; //
// writes
writes 8
8
}
}
22
22
0
7
xx:
yy:
a:
1st
call (refer to xx)
2nd
call (refer to yy)
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Functions
Functions
 Avoid (non-const) reference arguments when you can
Avoid (non-const) reference arguments when you can
 They can lead to obscure bugs when you forget which
They can lead to obscure bugs when you forget which
arguments can be changed
arguments can be changed
int incr1(int a) { return a+1; }
int incr1(int a) { return a+1; }
void incr2(int& a) { ++a; }
void incr2(int& a) { ++a; }
int x = 7;
int x = 7;
x = incr1(x);
x = incr1(x); //
// pretty obvious
pretty obvious
incr2(x);
incr2(x); //
// pretty obscure
pretty obscure
 So why have reference arguments?
So why have reference arguments?
 Occasionally, they are essential
Occasionally, they are essential
 E.g.,
E.g., for changing several values
for changing several values
 For manipulating containers (
For manipulating containers (e.g.,
e.g., vector)
vector)
 const
const reference arguments are very often useful
reference arguments are very often useful
23
23
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Call by value/by reference/
Call by value/by reference/
by const-reference
by const-reference
void f(int a, int& r, const int& cr) { ++a; ++r; ++cr; } //
void f(int a, int& r, const int& cr) { ++a; ++r; ++cr; } // error:
error: cr
cr is
is const
const
void g(int a, int& r, const int& cr) { ++a; ++r; int x = cr; ++x; } //
void g(int a, int& r, const int& cr) { ++a; ++r; int x = cr; ++x; } // ok
ok
int main()
int main()
{
{
int x = 0;
int x = 0;
int y = 0;
int y = 0;
int z = 0;
int z = 0;
g(x,y,z);
g(x,y,z); //
// x==0; y==1; z==0
x==0; y==1; z==0
g(1,2,3);
g(1,2,3);//
// error: reference argument
error: reference argument r
r needs a variable to refer to
needs a variable to refer to
g(1,y,3);
g(1,y,3);//
// ok: since
ok: since cr
cr is
is const
const we can pass “a temporary”
we can pass “a temporary”
}
}
//
// const
const references are very useful for passing large objects
references are very useful for passing large objects
24
24
Stroustrup/Programming/2015
Stroustrup/Programming/2015
References
References
 “
“reference” is a general concept
reference” is a general concept
 Not just for call-by-reference
Not just for call-by-reference
int i = 7;
int i = 7;
int& r = i;
int& r = i;
r = 9;
r = 9; //
// i
i becomes
becomes 9
9
const int& cr = i;
const int& cr = i;
// cr = 7;
// cr = 7; //
// error:
error: cr
cr refers to
refers to const
const
i = 8;
i = 8;
cout << cr << endl;
cout << cr << endl; //
// write out the value of i (that
write out the value of i (that’s
’s 8
8)
)
 You can
You can
 think of a reference as an alternative name for an object
think of a reference as an alternative name for an object
 You can’t
You can’t
 modify an object through a
modify an object through a const
const reference
reference
 make a reference refer to another object after initialization
make a reference refer to another object after initialization
25
25
7
i:
r
cr
Stroustrup/Programming/2015
Stroustrup/Programming/2015
For example
For example
 A range-for loop:
A range-for loop:
 for (string s : v) cout << s << ″n″;
for (string s : v) cout << s << ″n″; //
// s is a copy of
s is a copy of
some v[i]
some v[i]
 for (string& s : v) cout << s << ″n″;
for (string& s : v) cout << s << ″n″; //
// no copy
no copy
 for (const string& s : v) cout << s << ″n″;
for (const string& s : v) cout << s << ″n″; //
// and we don’t
and we don’t
modify v
modify v
Stroustrup/Programming/2015
Stroustrup/Programming/2015 26
26
Compile-time functions
Compile-time functions
 You can define functions that can be evaluated at compile time:
constexpr functions
constexpr double xscale = 10; // scaling factors
constexpr double yscale = .8;
constexpr Point scale(Point p) { return {xscale*p.x,yscale*p.y}; };
constexpr Point x = scale({123,456}); // evaluated at compile time
void use(Point p)
{
constexpr Point x1 = scale(p); // error: compile-time evaluation
// requested for variable argument
Point x2 = scale(p); // OK: run-time evaluation
}
Stroustrup/Programming/2015
Stroustrup/Programming/2015 27
27
Guidance for Passing Variables
Guidance for Passing Variables
 Use call-by-value for very small objects
Use call-by-value for very small objects
 Use call-by-const-reference for large objects
Use call-by-const-reference for large objects
 Use call-by-reference only when you have to
Use call-by-reference only when you have to
 Return a result rather than modify an object through a reference
Return a result rather than modify an object through a reference
argument
argument
 For example
For example
class Image { /*
class Image { /* objects are potentially huge
objects are potentially huge */ };
*/ };
void f(Image i); … f(my_image); //
void f(Image i); … f(my_image); // oops: this could be s-l-o-o-o-w
oops: this could be s-l-o-o-o-w
void f(Image& i); … f(my_image); //
void f(Image& i); … f(my_image); // no copy, but
no copy, but f()
f() can modify
can modify my_image
my_image
void f(const Image&); … f(my_image); //
void f(const Image&); … f(my_image); // f()
f() won
won’
’t mess with
t mess with my_image
my_image
Image make_image();
Image make_image(); //
// most likely fast! (“move semantics” – later)
most likely fast! (“move semantics” – later)
28
28
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Namespaces
Namespaces
 Consider this code from two programmers Jack and Jill
Consider this code from two programmers Jack and Jill
class Glob { /*
class Glob { /*…
…*/ };
*/ }; //
// in Jack
in Jack’s header file
’s header file jack.h
jack.h
class Widget { /*
class Widget { /*…
…*/ };
*/ }; //
// also in
also in jack.h
jack.h
class Blob { /*
class Blob { /*…
…*/ };
*/ }; //
// in Jill
in Jill’s header file
’s header file jill.h
jill.h
class Widget { /*
class Widget { /*…
…*/ };
*/ }; //
// also in
also in jill.h
jill.h
#include "jack.h";
#include "jack.h"; //
// this is in your code
this is in your code
#include "jill.h";
#include "jill.h"; //
// so is this
so is this
void my_func(Widget p)
void my_func(Widget p) //
// oops! – error: multiple definitions of Widget
oops! – error: multiple definitions of Widget
{
{
//
// …
…
}
}
29
29
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Namespaces
Namespaces
 The compiler will not compile multiple definitions; such clashes can occur from multiple headers.
The compiler will not compile multiple definitions; such clashes can occur from multiple headers.
 One way to prevent this problem is with namespaces:
One way to prevent this problem is with namespaces:
namespace Jack {
namespace Jack { //
// in Jack
in Jack’s header file
’s header file
class Glob{ /*
class Glob{ /*…
…*/ };
*/ };
class Widget{ /*
class Widget{ /*…
…*/ }
*/ };
;
}
}
#include "jack.h";
#include "jack.h"; //
// this is in your code
this is in your code
#include "jill.h";
#include "jill.h"; //
// so is this
so is this
void my_func(Jack::Widget p)
void my_func(Jack::Widget p) //
// OK, Jack
OK, Jack’s Widget class will not
’s Widget class will not
{
{ //
// clash with a different Widget
clash with a different Widget
//
// …
…
}
}
30
30
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Namespaces
Namespaces
 A namespace is a named scope
A namespace is a named scope
 The :: syntax is used to specify which namespace you are using
The :: syntax is used to specify which namespace you are using
and which (of many possible) objects of the same name you are
and which (of many possible) objects of the same name you are
referring to
referring to
 For example,
For example, cout
cout is in namespace
is in namespace std
std, you could write:
, you could write:
std::cout << "Please enter stuff… n";
std::cout << "Please enter stuff… n";
31
31
Stroustrup/Programming/2015
Stroustrup/Programming/2015
using
using Declarations and Directives
Declarations and Directives
 To avoid the tedium of
To avoid the tedium of
 std::cout << "Please enter stuff… n";
std::cout << "Please enter stuff… n";
you could write a “using declaration”
you could write a “using declaration”
 using std::cout;
using std::cout; //
// when I say
when I say cout
cout, I mean
, I mean std::cout
std::cout
 cout << "Please enter stuff… n";
cout << "Please enter stuff… n"; //
// ok: std::cout
ok: std::cout
 cin >> x;
cin >> x; //
// error: cin not in scope
error: cin not in scope
 or you could write a “using directive”
or you could write a “using directive”
 using namespace std; //
using namespace std; // “make all names from namespace
“make all names from namespace std
std
available”
available”
 cout << "Please enter stuff… n";
cout << "Please enter stuff… n"; //
// ok: std::cout
ok: std::cout
 cin >> x;
cin >> x; //
// ok: std::cin
ok: std::cin
 More about header files in chapter 12
More about header files in chapter 12
32
32
Stroustrup/Programming/2015
Stroustrup/Programming/2015
Next talk
Next talk
 More technicalities, mostly related to classes
More technicalities, mostly related to classes
33
33
Stroustrup/Programming/2015
Stroustrup/Programming/2015

More Related Content

PPTX
C++ programming language basic to advance level
PDF
Functions And Header Files In C++ | Bjarne stroustrup
DOCX
Apa style-1 (1)
DOC
Basic c
PPT
intro to programming languge c++ for computer department
PDF
Library management system
PPTX
Switch case looping
PDF
Objective c beginner's guide
C++ programming language basic to advance level
Functions And Header Files In C++ | Bjarne stroustrup
Apa style-1 (1)
Basic c
intro to programming languge c++ for computer department
Library management system
Switch case looping
Objective c beginner's guide

Similar to Functions, présentation des techniques pour une compréhention des fonctions en C++ (20)

PDF
C notes.pdf
DOCX
C tutorials
PDF
Basic Information About C language PDF
PPTX
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
PPT
1 2 programming
PPTX
Yeahhhh the final requirement!!!
DOCX
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
PDF
08 -functions
DOC
C notes diploma-ee-3rd-sem
PDF
Developing With Compile Time In Mind Richard Cattermole
PPTX
C Language ppt create by Anand & Sager.pptx
PPTX
Switch case and looping
PPT
Basics of c++
PDF
C fundamentals
PPTX
C Programming Unit-1
PDF
c++ referesher 1.pdf
PDF
C++primer
PPTX
Fundamentals of programming final santos
PPTX
Presentation 5th
PPT
1. overview of c
C notes.pdf
C tutorials
Basic Information About C language PDF
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
1 2 programming
Yeahhhh the final requirement!!!
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
08 -functions
C notes diploma-ee-3rd-sem
Developing With Compile Time In Mind Richard Cattermole
C Language ppt create by Anand & Sager.pptx
Switch case and looping
Basics of c++
C fundamentals
C Programming Unit-1
c++ referesher 1.pdf
C++primer
Fundamentals of programming final santos
Presentation 5th
1. overview of c
Ad

Recently uploaded (20)

PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
IGGE1 Understanding the Self1234567891011
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PDF
HVAC Specification 2024 according to central public works department
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
International_Financial_Reporting_Standa.pdf
PDF
advance database management system book.pdf
PDF
Complications of Minimal Access-Surgery.pdf
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PPTX
Virtual and Augmented Reality in Current Scenario
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
AI-driven educational solutions for real-life interventions in the Philippine...
Environmental Education MCQ BD2EE - Share Source.pdf
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
What if we spent less time fighting change, and more time building what’s rig...
FORM 1 BIOLOGY MIND MAPS and their schemes
Cambridge-Practice-Tests-for-IELTS-12.docx
IGGE1 Understanding the Self1234567891011
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
HVAC Specification 2024 according to central public works department
History, Philosophy and sociology of education (1).pptx
International_Financial_Reporting_Standa.pdf
advance database management system book.pdf
Complications of Minimal Access-Surgery.pdf
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
TNA_Presentation-1-Final(SAVE)) (1).pptx
Virtual and Augmented Reality in Current Scenario
Ad

Functions, présentation des techniques pour une compréhention des fonctions en C++

  • 1. Chapter 8 Chapter 8 Technicalities: Functions, etc. Technicalities: Functions, etc. Bjarne Stroustrup www.stroustrup.com/Programming
  • 2. Abstract Abstract  This lecture and the following present some technical This lecture and the following present some technical details of the language to give a slightly broader view details of the language to give a slightly broader view of C++’s basic facilities and to provide a more of C++’s basic facilities and to provide a more systematic view of those facilities. This also acts as a systematic view of those facilities. This also acts as a review of many of the notions presented so far, such review of many of the notions presented so far, such as types, functions, and initialization, and provides an as types, functions, and initialization, and provides an opportunity to explore our tool without adding new opportunity to explore our tool without adding new programming techniques or concepts. programming techniques or concepts. 2 2 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 3. Overview Overview  Language Technicalities Language Technicalities  Declarations Declarations  Definitions Definitions  Headers and the preprocessor Headers and the preprocessor  Scope Scope  Functions Functions  Declarations and definitions Declarations and definitions  Arguments Arguments  Call by value, reference, and Call by value, reference, and const const reference reference  Namespaces Namespaces  “ “Using” declarations Using” declarations 3 3 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 4. Language technicalities Language technicalities  Are a necessary evil Are a necessary evil  A programming language is a foreign language A programming language is a foreign language  When learning a foreign language, you have to look at the grammar and When learning a foreign language, you have to look at the grammar and vocabulary vocabulary  We will do this in this chapter and the next We will do this in this chapter and the next  Because: Because:  Programs must be precisely and completely specified Programs must be precisely and completely specified  A computer is a very stupid (though very fast) machine A computer is a very stupid (though very fast) machine  A computer can A computer can’t guess what you “really meant to say” (and shouldn’t try to) ’t guess what you “really meant to say” (and shouldn’t try to)  So we must know the rules So we must know the rules  Some of them (the C++14 standard is 1,358 pages) Some of them (the C++14 standard is 1,358 pages)  However, never forget that However, never forget that  What we study is programming What we study is programming  Our output is programs/systems Our output is programs/systems  A programming language is only a tool A programming language is only a tool 4 4 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 5. Technicalities Technicalities  Don’t spend your time on minor syntax and semantic issues. Don’t spend your time on minor syntax and semantic issues. There is more than one way to say everything There is more than one way to say everything  Just like in English Just like in English  Most design and programming concepts are universal, or at Most design and programming concepts are universal, or at least very widely supported by popular programming languages least very widely supported by popular programming languages  So what you learn using C++ you can use with many other languages So what you learn using C++ you can use with many other languages  Language technicalities are specific to a given language Language technicalities are specific to a given language  But many of the technicalities from C++ presented here have obvious But many of the technicalities from C++ presented here have obvious counterparts in C, Java, C#, etc. counterparts in C, Java, C#, etc. 5 5 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 6. Declarations Declarations  A declaration introduces a name into a scope. A declaration introduces a name into a scope.  A declaration also specifies a type for the named object. A declaration also specifies a type for the named object.  Sometimes a declaration includes an initializer. Sometimes a declaration includes an initializer.  A name must be declared before it can be used in a C++ program. A name must be declared before it can be used in a C++ program.  Examples: Examples:  int a = 7; int a = 7; // // an int variable named an int variable named ‘a’ is declared ‘a’ is declared  const double cd = 8.7; const double cd = 8.7; // // a double-precision floating-point constant a double-precision floating-point constant  double sqrt(double); double sqrt(double); // // a function taking a double argument and a function taking a double argument and // // returning a double result returning a double result  vector<Token> v; vector<Token> v; // // a vector variable of a vector variable of Token Tokens (variable) s (variable) 6 6 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 7. Declarations Declarations  Declarations are frequently introduced into a program through Declarations are frequently introduced into a program through “headers” “headers”  A header is a file containing declarations providing an interface to other A header is a file containing declarations providing an interface to other parts of a program parts of a program  This allows for abstraction – you don This allows for abstraction – you don’ ’t have to know the details t have to know the details of a function like of a function like cout cout in order to use it. When you add in order to use it. When you add #include "std_lib_facilities.h" #include "std_lib_facilities.h" to your code, the declarations in the file to your code, the declarations in the file std_lib_facilities.h std_lib_facilities.h become available (including become available (including cout cout, , etc.). etc.). 7 7 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 8. For example For example  At least three errors: At least three errors: int main() { cout << f(i) << ′n′; }  Add declarations: Add declarations: #include ″std_lib_facilities.h″ // we find the declaration of cout in here int main() { cout << f(i) << ′n′; } Stroustrup/Programming/2015 Stroustrup/Programming/2015 8 8
  • 9. For example For example  Define your own functions and variables: Define your own functions and variables: #include ″std_lib_facilities.h″ // we find the declaration of cout in here int f(int x ) { /* … */ } // declaration of f int main() { int i = 7; // declaration of i cout << f(i) << ′n′; } Stroustrup/Programming/2015 Stroustrup/Programming/2015 9 9
  • 10. Definitions Definitions A declaration that (also) fully specifies the entity declared is A declaration that (also) fully specifies the entity declared is called a definition called a definition  Examples Examples int a = 7; int a = 7; int b; int b; // // an (uninitialized) int an (uninitialized) int vector<double> v; vector<double> v; // // an empty vector of doubles an empty vector of doubles double sqrt(double) { … }; // double sqrt(double) { … }; // a function with a body a function with a body struct Point { int x; int y; }; struct Point { int x; int y; };  Examples of declarations that are not definitions Examples of declarations that are not definitions double sqrt(double); double sqrt(double); // // function body missing function body missing struct Point; struct Point; // // class members specified elsewhere class members specified elsewhere extern int a; extern int a; // // extern extern means means “not definition” “not definition” // // “extern” is archaic; we will hardly use it “extern” is archaic; we will hardly use it 10 10 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 11. Declarations and definitions Declarations and definitions  You can’t You can’t define define something twice something twice  A definition says what something is A definition says what something is  Examples Examples int a; int a; // // definition definition int a; int a; // // error: double definition error: double definition double sqrt(double d) { … } double sqrt(double d) { … } // // definition definition double sqrt(double d) { … } double sqrt(double d) { … } // // error: double definition error: double definition  You can You can declare declare something twice something twice  A declaration says how something can be used A declaration says how something can be used int a = 7; int a = 7; // // definition (also a declaration) definition (also a declaration) extern int a; extern int a; // // declaration declaration double sqrt(double); double sqrt(double); // // declaration declaration double sqrt(double d) { … } double sqrt(double d) { … } // // definition (also a declaration) definition (also a declaration) 11 11 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 12. Why both declarations and Why both declarations and definitions? definitions?  To refer to something, we need (only) its declaration To refer to something, we need (only) its declaration  Often we want the definition “elsewhere” Often we want the definition “elsewhere”  Later in a file Later in a file  In another file In another file  preferably written by someone else preferably written by someone else  Declarations are used to specify interfaces Declarations are used to specify interfaces  To your own code To your own code  To libraries To libraries  Libraries are key: we can Libraries are key: we can’t write all ourselves, and wouldn’t want to ’t write all ourselves, and wouldn’t want to  In larger programs In larger programs  Place all declarations in header files to ease sharing Place all declarations in header files to ease sharing 12 12 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 13. Kinds of declarations  The most interesting are  Variables  int x;  vector<int> vi2 {1,2,3,4};  Constants  void f(const X&);  constexpr int = isqrt(2);  Functions (see §8.5)  double sqrt(double d) { /* … */ }  Namespaces (see §8.7)  Types (classes and enumerations; see Chapter 9)  Templates (see Chapter 19) Stroustrup/Programming/2015 Stroustrup/Programming/2015 13 13
  • 14. Header Files and the Preprocessor Header Files and the Preprocessor  A header is a file that holds declarations of functions, types, A header is a file that holds declarations of functions, types, constants, and other program components. constants, and other program components.  The construct The construct #include #include "std_lib_facilities.h" "std_lib_facilities.h" is a is a “ “preprocessor directive preprocessor directive” ” that adds that adds declarations to your declarations to your program program  Typically, the header file is simply a text (source code) file Typically, the header file is simply a text (source code) file  A header gives you access to functions, types, etc. that you A header gives you access to functions, types, etc. that you want to use in your programs. want to use in your programs.  Usually, you don Usually, you don’t really care about how they are written. ’t really care about how they are written.  The actual functions, types, etc. are defined in other source code files The actual functions, types, etc. are defined in other source code files  Often as part of libraries Often as part of libraries 14 14 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 15. Source files Source files  A header file (here, A header file (here, token.h token.h) defines an interface between user code ) defines an interface between user code and implementation code (usually in a library) and implementation code (usually in a library)  The same The same #include #include declarations in both declarations in both .cpp .cpp files (definitions and files (definitions and uses) ease consistency checking uses) ease consistency checking 15 15 // declarations: class Token { … }; class Token_stream { Token get(); … }; extern Token_stream ts; … #include "token.h" //definitions: Token Token_stream::get() { /* … */ } Token_stream ts; … #include "token.h" … Token t = ts.get(); … token.h: token.cpp: use.cpp: Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 16. Scope Scope  A scope is a region of program text A scope is a region of program text  Global scope (outside any language construct) Global scope (outside any language construct)  Class scope (within a class) Class scope (within a class)  Local scope (between { … } braces) Local scope (between { … } braces)  Statement scope (e.g. in a for-statement) Statement scope (e.g. in a for-statement)  A name in a scope can be seen from within its scope and within A name in a scope can be seen from within its scope and within scopes nested within that scope scopes nested within that scope  Only after the declaration of the name ( Only after the declaration of the name (“can’t look ahead” rule) “can’t look ahead” rule)  Class members can be used within the class before they are declared Class members can be used within the class before they are declared  A scope keeps “things” local A scope keeps “things” local  Prevents my variables, functions, etc., from interfering with yours Prevents my variables, functions, etc., from interfering with yours  Remember: real programs have Remember: real programs have many many thousands of entities thousands of entities  Locality is good! Locality is good!  Keep names as local as possible Keep names as local as possible 16 16 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 17. Scope Scope #include "std_lib_facilities.h" #include "std_lib_facilities.h" // // get get max max and and abs abs from here from here // // no no r, i, r, i, or or v v here here class My_vector { class My_vector { vector<int> v; vector<int> v; // // v v is in class scope is in class scope public: public: int largest() int largest() // // largest largest is in class scope is in class scope { { int r = 0; int r = 0; // // r r is local is local for (int i = 0; i<v.size(); ++i) for (int i = 0; i<v.size(); ++i) // // i i is in statement scope is in statement scope r = max(r,abs(v[i])); r = max(r,abs(v[i])); // // no no i i here here return r; return r; } } // // no no r r here here }; }; // // no no v v here here 17 17 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 18. Scopes nest Scopes nest int x; int x; // // global variable – avoid those where you can global variable – avoid those where you can int y; int y; // // another global variable another global variable int f() int f() { { int x; int x; // // local variable (Note – now there are two local variable (Note – now there are two x x’s) ’s) x = 7; x = 7; // // local local x x, not the global , not the global x x { { int x = y; int x = y; // // another local another local x x, initialized by the global , initialized by the global y y // // (Now there are three (Now there are three x x’s) ’s) ++x; ++x; // // increment the local increment the local x x in this scope in this scope } } } } // // avoid such complicated nesting and hiding: keep it simple! avoid such complicated nesting and hiding: keep it simple! 18 18 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 19. Recap: Why functions? Recap: Why functions?  Chop a program into manageable pieces Chop a program into manageable pieces  “ “divide and conquer” divide and conquer”  Match our understanding of the problem domain Match our understanding of the problem domain  Name logical operations Name logical operations  A function should do one thing well A function should do one thing well  Functions make the program easier to read Functions make the program easier to read  A function can be useful in many places in a program A function can be useful in many places in a program  Ease testing, distribution of labor, and maintenance Ease testing, distribution of labor, and maintenance  Keep functions small Keep functions small  Easier to understand, specify, and debug Easier to understand, specify, and debug Stroustrup/Programming/2015 Stroustrup/Programming/2015 19 19
  • 20. Functions Functions  General form: General form:  return_type return_type name name ( (formal arguments formal arguments); ); // // a a declaration declaration  return_type return_type name name ( (formal arguments formal arguments) ) body body // // a a definition definition  For example For example double f(int a, double d) { return a*d; } double f(int a, double d) { return a*d; }  Formal arguments are often called parameters Formal arguments are often called parameters  If you don’t want to return a value give If you don’t want to return a value give void void as the return type as the return type void increase_power_to(int level); void increase_power_to(int level);  Here, Here, void void means means “doesn’t return a value” “doesn’t return a value”  A body is a block or a try block A body is a block or a try block  For example For example { /* { /* code code */ } */ } // // a block a block try { /* try { /* code code */ } catch(exception& e) { /* */ } catch(exception& e) { /* code code */ } */ } // // a try block a try block  Functions represent/implement computations/calculations Functions represent/implement computations/calculations 20 20 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 21. Functions: Call by Value Functions: Call by Value // // call-by-value (send the function a copy of the argument’s value) call-by-value (send the function a copy of the argument’s value) int f(int a) { a = a+1; return a; } int f(int a) { a = a+1; return a; } int main() int main() { { int xx = 0; int xx = 0; cout << f(xx) << cout << f(xx) << ′n′; ; // // writes writes 1 1 cout << xx << cout << xx << ′n′; ; // // writes writes 0; f() 0; f() doesn’t change doesn’t change xx xx int yy = 7; int yy = 7; cout << f(yy) << cout << f(yy) << ′n′; // ; // writes writes 8; f() 8; f() doesn’t change doesn’t change yy yy cout << yy << cout << yy << ′n′; ; // // writes writes 7 7 } } 21 21 0 a: xx: copy the value 0 7 a: yy: copy the value 7 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 22. Functions: Call by Reference Functions: Call by Reference // // call-by-reference (pass a reference to the argument) call-by-reference (pass a reference to the argument) int f(int& a) { a = a+1; return a; } int f(int& a) { a = a+1; return a; } int main() int main() { { int xx = 0; int xx = 0; cout << f(xx) << cout << f(xx) << ′n′; ; // // writes writes 1 1 // // f() f() changed the value of changed the value of xx xx cout << xx << cout << xx << ′n′; ; // // writes writes 1 1 int yy = 7; int yy = 7; cout << f(yy) << cout << f(yy) << ′n′; // ; // writes writes 8 8 // // f() f() changes the value of changes the value of yy yy cout << yy << cout << yy << ′n′; ; // // writes writes 8 8 } } 22 22 0 7 xx: yy: a: 1st call (refer to xx) 2nd call (refer to yy) Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 23. Functions Functions  Avoid (non-const) reference arguments when you can Avoid (non-const) reference arguments when you can  They can lead to obscure bugs when you forget which They can lead to obscure bugs when you forget which arguments can be changed arguments can be changed int incr1(int a) { return a+1; } int incr1(int a) { return a+1; } void incr2(int& a) { ++a; } void incr2(int& a) { ++a; } int x = 7; int x = 7; x = incr1(x); x = incr1(x); // // pretty obvious pretty obvious incr2(x); incr2(x); // // pretty obscure pretty obscure  So why have reference arguments? So why have reference arguments?  Occasionally, they are essential Occasionally, they are essential  E.g., E.g., for changing several values for changing several values  For manipulating containers ( For manipulating containers (e.g., e.g., vector) vector)  const const reference arguments are very often useful reference arguments are very often useful 23 23 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 24. Call by value/by reference/ Call by value/by reference/ by const-reference by const-reference void f(int a, int& r, const int& cr) { ++a; ++r; ++cr; } // void f(int a, int& r, const int& cr) { ++a; ++r; ++cr; } // error: error: cr cr is is const const void g(int a, int& r, const int& cr) { ++a; ++r; int x = cr; ++x; } // void g(int a, int& r, const int& cr) { ++a; ++r; int x = cr; ++x; } // ok ok int main() int main() { { int x = 0; int x = 0; int y = 0; int y = 0; int z = 0; int z = 0; g(x,y,z); g(x,y,z); // // x==0; y==1; z==0 x==0; y==1; z==0 g(1,2,3); g(1,2,3);// // error: reference argument error: reference argument r r needs a variable to refer to needs a variable to refer to g(1,y,3); g(1,y,3);// // ok: since ok: since cr cr is is const const we can pass “a temporary” we can pass “a temporary” } } // // const const references are very useful for passing large objects references are very useful for passing large objects 24 24 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 25. References References  “ “reference” is a general concept reference” is a general concept  Not just for call-by-reference Not just for call-by-reference int i = 7; int i = 7; int& r = i; int& r = i; r = 9; r = 9; // // i i becomes becomes 9 9 const int& cr = i; const int& cr = i; // cr = 7; // cr = 7; // // error: error: cr cr refers to refers to const const i = 8; i = 8; cout << cr << endl; cout << cr << endl; // // write out the value of i (that write out the value of i (that’s ’s 8 8) )  You can You can  think of a reference as an alternative name for an object think of a reference as an alternative name for an object  You can’t You can’t  modify an object through a modify an object through a const const reference reference  make a reference refer to another object after initialization make a reference refer to another object after initialization 25 25 7 i: r cr Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 26. For example For example  A range-for loop: A range-for loop:  for (string s : v) cout << s << ″n″; for (string s : v) cout << s << ″n″; // // s is a copy of s is a copy of some v[i] some v[i]  for (string& s : v) cout << s << ″n″; for (string& s : v) cout << s << ″n″; // // no copy no copy  for (const string& s : v) cout << s << ″n″; for (const string& s : v) cout << s << ″n″; // // and we don’t and we don’t modify v modify v Stroustrup/Programming/2015 Stroustrup/Programming/2015 26 26
  • 27. Compile-time functions Compile-time functions  You can define functions that can be evaluated at compile time: constexpr functions constexpr double xscale = 10; // scaling factors constexpr double yscale = .8; constexpr Point scale(Point p) { return {xscale*p.x,yscale*p.y}; }; constexpr Point x = scale({123,456}); // evaluated at compile time void use(Point p) { constexpr Point x1 = scale(p); // error: compile-time evaluation // requested for variable argument Point x2 = scale(p); // OK: run-time evaluation } Stroustrup/Programming/2015 Stroustrup/Programming/2015 27 27
  • 28. Guidance for Passing Variables Guidance for Passing Variables  Use call-by-value for very small objects Use call-by-value for very small objects  Use call-by-const-reference for large objects Use call-by-const-reference for large objects  Use call-by-reference only when you have to Use call-by-reference only when you have to  Return a result rather than modify an object through a reference Return a result rather than modify an object through a reference argument argument  For example For example class Image { /* class Image { /* objects are potentially huge objects are potentially huge */ }; */ }; void f(Image i); … f(my_image); // void f(Image i); … f(my_image); // oops: this could be s-l-o-o-o-w oops: this could be s-l-o-o-o-w void f(Image& i); … f(my_image); // void f(Image& i); … f(my_image); // no copy, but no copy, but f() f() can modify can modify my_image my_image void f(const Image&); … f(my_image); // void f(const Image&); … f(my_image); // f() f() won won’ ’t mess with t mess with my_image my_image Image make_image(); Image make_image(); // // most likely fast! (“move semantics” – later) most likely fast! (“move semantics” – later) 28 28 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 29. Namespaces Namespaces  Consider this code from two programmers Jack and Jill Consider this code from two programmers Jack and Jill class Glob { /* class Glob { /*… …*/ }; */ }; // // in Jack in Jack’s header file ’s header file jack.h jack.h class Widget { /* class Widget { /*… …*/ }; */ }; // // also in also in jack.h jack.h class Blob { /* class Blob { /*… …*/ }; */ }; // // in Jill in Jill’s header file ’s header file jill.h jill.h class Widget { /* class Widget { /*… …*/ }; */ }; // // also in also in jill.h jill.h #include "jack.h"; #include "jack.h"; // // this is in your code this is in your code #include "jill.h"; #include "jill.h"; // // so is this so is this void my_func(Widget p) void my_func(Widget p) // // oops! – error: multiple definitions of Widget oops! – error: multiple definitions of Widget { { // // … … } } 29 29 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 30. Namespaces Namespaces  The compiler will not compile multiple definitions; such clashes can occur from multiple headers. The compiler will not compile multiple definitions; such clashes can occur from multiple headers.  One way to prevent this problem is with namespaces: One way to prevent this problem is with namespaces: namespace Jack { namespace Jack { // // in Jack in Jack’s header file ’s header file class Glob{ /* class Glob{ /*… …*/ }; */ }; class Widget{ /* class Widget{ /*… …*/ } */ }; ; } } #include "jack.h"; #include "jack.h"; // // this is in your code this is in your code #include "jill.h"; #include "jill.h"; // // so is this so is this void my_func(Jack::Widget p) void my_func(Jack::Widget p) // // OK, Jack OK, Jack’s Widget class will not ’s Widget class will not { { // // clash with a different Widget clash with a different Widget // // … … } } 30 30 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 31. Namespaces Namespaces  A namespace is a named scope A namespace is a named scope  The :: syntax is used to specify which namespace you are using The :: syntax is used to specify which namespace you are using and which (of many possible) objects of the same name you are and which (of many possible) objects of the same name you are referring to referring to  For example, For example, cout cout is in namespace is in namespace std std, you could write: , you could write: std::cout << "Please enter stuff… n"; std::cout << "Please enter stuff… n"; 31 31 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 32. using using Declarations and Directives Declarations and Directives  To avoid the tedium of To avoid the tedium of  std::cout << "Please enter stuff… n"; std::cout << "Please enter stuff… n"; you could write a “using declaration” you could write a “using declaration”  using std::cout; using std::cout; // // when I say when I say cout cout, I mean , I mean std::cout std::cout  cout << "Please enter stuff… n"; cout << "Please enter stuff… n"; // // ok: std::cout ok: std::cout  cin >> x; cin >> x; // // error: cin not in scope error: cin not in scope  or you could write a “using directive” or you could write a “using directive”  using namespace std; // using namespace std; // “make all names from namespace “make all names from namespace std std available” available”  cout << "Please enter stuff… n"; cout << "Please enter stuff… n"; // // ok: std::cout ok: std::cout  cin >> x; cin >> x; // // ok: std::cin ok: std::cin  More about header files in chapter 12 More about header files in chapter 12 32 32 Stroustrup/Programming/2015 Stroustrup/Programming/2015
  • 33. Next talk Next talk  More technicalities, mostly related to classes More technicalities, mostly related to classes 33 33 Stroustrup/Programming/2015 Stroustrup/Programming/2015