using
declarations do not obey block
scope. Write a small piece of code, which, when compiled, will convincingly
demonstrate that your friend's belief is wrong.
#include <iostream> void t(void) { { using std::out; cout << "hello\n"; // Ok. } cout << "hello\n"; // Not ok. }
const int i;
The declaration statement doesn't assign i
a value. the statement should
be
const int i =
expr;
int main() { int a[] = { 0, 1, 2, 3 }; // Note that a[i] == i for 0 <= i < 4. int i, j, k; i = j // Assume 0 <= j < 4; k = ?; // The mystery statement. if ((a[j] == j) && (k == j + 1)) cout << "Yes!\n"; }
which, if any, of the following expressions could be substituted for the ?
in the mystery statement to have the program print Yes!
when run:
a[i++]++
a[++i]++
++a[i++]
++a[++i]
Justify your answer.
The expression i++
returns the value of j
, which means that both
a[i++]++
and ++a[i++]
are equivalent to a[j]++
and ++a[j]
respectively. Either of these two expressions increases the value of a[j]
by one, which would make a[j] == j
be false. Replacing ?
with
either a or c would not print Yes!
.
The expression ++i
returns the value of j + 1
, which means that both
a[++i]++
and ++a[++i]
are equivalent to a[j + 1]++
and ++a[j
+ 1]
respectively. The value of a[j + 1]
is j + 1
, so a[j +
1]++
sets k
to j + 1
and ++a[j + 1]
sets k
to j + 2
.
Substituting d for ?
makes k == j + 1
false, while substituting b for
?
makes k == j + 1
true.
Substituting b for ?
makes both a[j] == j
and k == j + 1
true,
printing Yes!
.
if (
b-expr) ;
Assume b-expr is any syntactically correct boolean expression.
It's syntactically correct, although logically nonsensical. A semicolon with no statement is known as a empty statement. Because errant semicolons are a source of subtle programming errors, the preferred way to indicate empty statements is with a pair of braces:
if (
b-expr) { }
This page last modified on 21 September 2001.