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
  • 1
    Are you putting an empty line before #define ASSERT(x)\ if(!(x))\ ? Try taking out the empty line if you are. Commented Oct 28, 2010 at 1:40
  • You probably have an empty line after a macro definition line ending with a backslash. You must keep your macro definition lines together, ending each line with a backslash. Commented Oct 28, 2010 at 1:40

1 Answer 1

2
if(!(x))\
{\
       cout<<"Error!!Assert"<<#x<<"failed\n";\
       cout<<"on line"<<__LINE__<<"\n";\
       cout<<"in file"<<__FILE__<<"\n";\
} // no backslash
Sign up to request clarification or add additional context in comments.

6 Comments

Except surely you mean /*no backslash*/, in case the Original Poster's code has a line like ASSERT(x); DoSomethingImportant(); :-)
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 the // would comment out DoSomethingImportant().
@Jon: Doesn't tokenization (including comment removal) occur before macro expansion?
@Uncle there is one compiler i know (nvcc) that goes crazy having '//' in macros. :-(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.