Ramila
Ramila

Reputation: 145

using a simple assert() macro

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.

Upvotes: 1

Views: 1520

Answers (1)

Anycorn
Anycorn

Reputation: 51565

if(!(x))\
{\
       cout<<"Error!!Assert"<<#x<<"failed\n";\
       cout<<"on line"<<__LINE__<<"\n";\
       cout<<"in file"<<__FILE__<<"\n";\
} // no backslash

Upvotes: 2

Related Questions