读书人

为何这个程序编译通不过呢

发布时间: 2013-01-11 11:57:35 作者: rapoo

为什么这个程序编译通不过呢
这个程序是teach yourself cpp in 21 days中的代码
可是为什么我编译出错呢

// Listing 21.3 ASSERTS
#define DEBUG
#include <iostream>
using namespace std;
#ifndef DEBUG
#define ASSERT(x)
#else
#define ASSERT(x) \
if (! (x)) \
{ \
cout << "ERROR! Assert " << x << "failed" << endl; \
cout << " on line " << __LINE__ << endl; \
cout << " in file " << __FILE__ << endl; \
}
#endif

int main()
{
int x = 5;
cout << "First assert: " << endl;
ASSERT(x==5);
cout << "\nSecond assert: " << endl;
ASSERT(x != 5);
cout << "\nDone. << endl";
return 0;
}

[解决办法]
典型错误啊,宏是直接展开的,因此为了避免展开后的隐患,把参数用()括起了,这样改就OK了:

#ifndef DEBUG
#define ASSERT(x)
#else
#define ASSERT(x) \
if (! ((x))) \
{ \
cout << "ERROR! Assert " << (x) << "failed" << endl; \
cout << " on line " << __LINE__ << endl; \
cout << " in file " << __FILE__ << endl; \
}
#endif


引用:
这个程序是teach yourself cpp in 21 days中的代码
可是为什么我编译出错呢
C/C++ code?1234567891011121314151617181920212223242526// Listing 21.3 ASSERTS#define DEBUG#include <iostream>using namespace std;#ifnd……

[解决办法]
cout << "ERROR! Assert " << #x << "failed" << endl; \
这才是你要的东西……

读书人网 >C++

热点推荐