Reputation: 23
A friend of mine told me that this code has some problems:
#include <iostream>
#include <cstdio>
using namespace std;
#define cout printf
int main(){
cout("cout");
}
He didn't give me the reason and asked me to figure it out which I couldn't. The code seems to be working fine, what could possibly be wrong with it?
Upvotes: 0
Views: 615
Reputation: 92864
As far as I know the Standard forbids defining names (with #define) declared in any standard library header.
Found this in n3290 ($17.6.4.3.1)
17.6.4.3.1 Macro names [macro.names]
1 A translation unit that includes a standard library header shall not #define or #undef names declared in any standard library header.
Upvotes: 11
Reputation: 231163
You have declared In C++ you don't have to main
as returning int
, but have not included a return
statement. You should add a return 0;
to the end of the main
function.return
a value from main
, but it's good style.
Oh, and don't #define cout printf
, it's really confusing. It may not be technically illegal, but it's not nice for whoever comes later to try to maintain your code.
Upvotes: 0
Reputation: 361472
Yes. It has problem.
Since its C++, one may habitually write cout << 1000
which would be an error in this case, but which is otherwise very normal in C++.
What next? Are you trying to define this:
#define scanf cin
//so that you can use it as
scanf >> variable; //not so kewl.
My advice is :
Don't try to change the meaning of such names. What will you get by doing so, after all? Nothing.
Upvotes: 2
Reputation: 141810
While you may argue that this code "seems to be working fine", consider a few years down the line when your 7-line source file is a 7-hundred-line source file and you are not the only maintainer.
You've moved on from writing C-style printf
statements in C++ source files and you add (or another maintainer adds) the following line of perfectly valid C++:
cout << "What is wrong with my perfectly valid C++ code? " << endl;
And your compiler reports:
test.cpp:699: error: invalid operands of types ‘int ()(const char*, ...)’ and ‘const char [29]’ to binary ‘operator<<’
A whole world of pain!
Upvotes: 2
Reputation: 283664
It's got maintenance problems, because you'd redefined well-known features to work differently. So no other programmer will want to work on this code.
Similar:
#define MULTIPLY(a, b) (a + b)
#define FIVE 12
#define THREE 3
int main(void)
{
return MULTIPLY(FIVE, THREE);
}
It gives the right answer, but is totally unmaintainable.
Upvotes: 1