1

I was just developing a simple stack program in C++.

#include<iostream>
#define MAX 3;
using namespace std;

class stack
{
private:
    int arr[3];
    int top;

public:
    stack()
    {
        top=-1;
    }
    void push(int item)
    {
        if(top==MAX-1)
        {
            cout<<endl<<"STACK FULL";
            return;
        }
        top++;
        arr[top]=item;
        cout<<endl<<"Pushed "<<item;
    }
    int pop()
    {
        if(top==-1)
        {
            cout<<endl<<"STACK EMPTY";
            return NULL;
        }
        int temp=arr[top];
        top--;
        return temp;
    }
};

int main()
{
    stack s;
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);

    cout<<endl<<"Popped "<<s.pop();
    cout<<endl<<"Popped "<<s.pop();
    cout<<endl<<"Popped "<<s.pop();
    cout<<endl<<"Popped "<<s.pop();
}

and I got this as a gift

naveen@linuxmint ~/Desktop/C++ $ g++ stack.cpp -o stack
stack.cpp: In member function ‘void stack::push(int)’:
stack.cpp:18:11: error: expected ‘)’ before ‘;’ token
stack.cpp:18:16: error: expected ‘;’ before ‘)’ token
stack.cpp: In member function ‘int stack::pop()’:
stack.cpp:32:11: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]

When I remove # define MAX 3 and return NULL I get no error .Why is it giving errors?

Naveen
  • 7,944
  • 12
  • 78
  • 165

2 Answers2

19

Remove the ; from your define MAX 3 ; line. That will expand to something like

if(top==3 ;-1)

which is definitely not what you want. Remember that #define is a preprocessor directive, not a C statement.

A probably even better idea would be to change it to a constant rather than a #define using something like

static const unsigned MAX = 3;

which avoids all the preprocessor entirely.

Philip Kendall
  • 4,304
  • 1
  • 23
  • 42
12

It is not a good idea to define constants in #define.

Change #define MAX 3; to #define MAX 3

A related article for this:- Do not conclude macro definitions with a semicolon

An alternative could be:-

static const unsigned MAX = 3;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331