tags:

views:

93

answers:

1

I'm new to programming & i found this code when i was going through a book. I believe it gives an example of how to use a defined assert() macro. It doesn't compile on code::blocks 10.05. I get errors such as

  1. '#' is not followed by a macro parameter
  2. unterminated #else
  3. in function 'int main()' 'ASSERT' was not declared in this scope

Code:

#include<iostream>
#define DEBUG

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

using namespace std;

int main()
{
    int x = 5;
    cout<<"\nFirst assert.";
    ASSERT(x==5);
    cout<<"\nSecond assert.";
    ASSERT(x!=5);
    cout<<"\nDone."<<endl;

    return 0;
}

Any help would be greatly appreciated. Thanks in advance.

+2  A: 
if(!(x))\
{\
       cout<<"Error!!Assert"<<#x<<"failed\n";\
       cout<<"on line"<<__LINE__<<"\n";\
       cout<<"in file"<<__FILE__<<"\n";\
} // no backslash
aaa
Except surely you mean `/*no backslash*/`, in case the Original Poster's code has a line like `ASSERT(x); DoSomethingImportant();` :-)
Jon Rodriguez
@Jon hmm, yes.. bit tricky
aaa
I don't see a problem with the comments. What you would have a problem with is usages like: `if (x) ASSERT(y) else foobar(z);`
UncleBens
Removing the backslash did the trick. Thanks a lot.
Ramila
@UncleBens the // would comment out DoSomethingImportant().
Jon Rodriguez
@Jon: Doesn't tokenization (including comment removal) occur before macro expansion?
UncleBens
@Uncle there is one compiler i know (nvcc) that goes crazy having '//' in macros. :-(
aaa
@UncleBens: You're right (says http://en.wikipedia.org/wiki/C_preprocessor#Phases). Thanks for pointing that out.
Jon Rodriguez