开发者

What is NULL, does it need to be declared?

In this snippet I found here for a simple C++ hash everywhere there is a NULL I get a

NULL was not declared in this scope.

I'm using MinGW compiler g++. My guess is that NULL is not a reserved keyword? How could I determine the version of gcc and look at a reference list for C++ keywords?

This list here states that NULL is not a keyword.

int main()
  {
  }

const int TABLE_SIZE = 128;
class HashEntry 
  {
  private:
    int key;
    int value;
  public:
    HashEntry(int key, int value) 
      {
      this->key = key;
      this->value = value;
      }
    int getKey() 
      {
      return key;
      }
    int getValue() 
      {
      return value;
      }
  }; 
class HashMap 
  {
  private:
    HashEntry **table;
  public:
    HashMap() 
      {
      table = new HashEntry*[TABLE_SIZE];
      for (int i = 0; i < TABLE_SIZE; i++) table[i] = NULL;
      }
    int get(int key) 
      {
      int hash = (key % TABLE_SIZE);
      while (table[hash] != NULL && table[hash]->getKey() != key) hash = (hash + 1) % TABLE_SIZE;
      if (table[hash] == NULL)return -1;
      else return table[hash]->getValue();
开发者_开发百科      }
    void put(int key, int value) 
      {
      int hash = (key % TABLE_SIZE);
      while (table[hash] != NULL && table[hash]->getKey() != key)
      hash = (hash + 1) % TABLE_SIZE;
      if (table[hash] != NULL) delete table[hash];
      table[hash] = new HashEntry(key, value);
      }     
    ~HashMap() 
      {
      for (int i = 0; i < TABLE_SIZE; i++)
        if (table[i] != NULL) delete table[i];
      delete[] table;
      }
};


NULL is a standard macro declared in stddef.h. You need to include stddef.h (or cstddef) in order to use NULL.

You can always use 0 in place of NULL, if you don't want to include anything.


As mentioned elsewhere NULL is defined in stddef.h, and probably also in some other system header files (I have not checked this recently).

If you're using only C++ and not including anything then you can write:

#define NULL 0

at the top of your file and it will work as expected.

In newer C++0x or C++11 compilers have a keyword nullptr which should be used instead of NULL or 0 where pointers are concerned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜