ram@zedat.fu-berlin.de (Stefan Ram) wrote in news:using-namespace-std-
20100327145229@ram.dialup.fu-berlin.de:
Juha Nieminen <nospam@thanks.invalid> writes:
Gil Trude wrote:
Becareful with the word count, as <algorithm> uses the same word.
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 5 };
cout << std::count(arr, arr+10, 5);
Which is exactly why the expression "using namespace std;" should be
removed from the C++ standard and cause a compiler error.
For teaching purposes, I would like to see an example of
source code that fails spectacularly (under every C++
implementation) due to an inconspicuous usage of ?using
namespace std;?. The code should:
- fail to behave as expected by a beginnner reading it,
- this failure should be caused by the usage of
?using namespace std;?,
- but it should not be obvious to a beginner that this
causes the problem,
- so I would get the message ?using "using namespace
std;"? might cause bugs that are hard to find for
beginners.
Does this qualify?
#include <iostream> // for cout
#include <stdlib.h> // for rand()
#include <algorithm> // for generate
#include <math.h> // for sin()/cos()
using namespace std;
const double pi = 3.141592653589793;
/// Rotate a point (x, y) by an angle alpha
void rotate(double* x, double* y, double alpha) {
double x1 = cos(alpha)* (*x) + sin(alpha)* (*y);
double y1 = -sin(alpha)* (*x) + cos(alpha)* (*y);
*x = x1;
*y = y1;
}
int main() {
const int N=10;
double angles[N];
// generate N random angles in degrees
generate(angles, angles+N, rand);
// rotate the same point by each angle
for (int i=0; i<N; ++i) {
double x=10.0, y .0;
// convert angle to radians
double alpha=angles[i]*pi/180.0;
// rotate the point
rotate(&x, &y, &alpha);