for
statement allows the index variable to be declared within the for
statement itself, which limits the scope of the index to the for:
for (int i = 0; i < 10; i++) { std::cout << i << "\n"; // Ok, i defined. } std::cout << i << "\n"; // Not ok, i is not defined.
The while
statement does not have this feature. Show how it can be
simulated using standard C++ features; that is, show how the effect of
while (int i = expr) { body }
can be implemented using standard C++. Assume the value of the declaration statement
int i = expr
is the value of the expression
This code is almost the same as the code given in the Koenig and Moo to
implement a for
loop:
{ int i = expr; while (i) { body i = expr } }
This code can be simplified a bit by using the fact that the expression v =
e
returns the value of e
:
{ int i; while (i = expr) { body } }
In addition to being shorter than the original, this code also handles the case
where body has a continue
statement.
This form of the while
statement was originally proposed for inclusion to
the C++ standard, but it was never accepted.
One code example is
#include <iostream> int main() { std::cout << "before read, cin.eof() = " << std::cin.eof() << "\n"; char c; std.cin >> c; std::cout << "after read, cin.eof() = " << std::cin.eof() << "\n"; }
When compiled and run with cin
connected to an empty file (such as
/dev/null
), it produces
$ g++ -ansi -pedantic -Wall t.cc $ a.out < /dev/null before read, cin.eof() = 0 after read, cin.eof() = 1 $
It's Koenig and Moo's notation for cross-references; "§s/p" refers to the part of Section s found on page p; in the example given, it refers to the part of Section 39.4.3 found on page 857.
std::string s1 = "ho" + h1 + h2; // Compile time type error. std::string s2 = "ho" + h2 + h1; // No compile time type error.
What are the types of h1
and h2
? Explain.
Looking at the declaration for s2
, "ho" + h2
compiles without error,
so it must be that h2
has type std::string
or int
. If h2
has type std::string
, then h1
must have type std::string
or
char *
. If h2
has type int
, then h1
must have type
int
. To summarize, the three possibilities arising from s2
's
declaration are
string = char * + int + int
string = char * + string + string
string = char * + string + char *
Looking at the declaration for s1
, we can eliminate possibility 1 because
if
char * + int + int
is legal for s2
, it's also legal for s1
, which is contrary to the
claim made in the problem statement. By similar reasoning, we can eliminate
possibility 2. That leaves only possibility 3. Checking against the problem
statement, with h2
of type std::string
and h1
of type char
*
we get
char * + string + char *
is legal as claimed, and
char * + char * + string
is illegal as claimed.
This page last modified on 21 September 2001.