0

I know with pointers you can do this:

T * myPtr = 0;

which sets the pointer to a NULL value. However, when I try to do this:

T * myPtrArray[2] = {0, 0};

I get the "expected expression" syntax error. Why?

Note, I'm using g++ and the code above occurs in a class constructor:

template <class T>
    RBTree<T>::RBTree() {
        m_Data = T();
        m_Children = {0, 0};
        m_Parent = 0;
        m_Color = BLACK;
    }

where the class members in question are declared as:

T m_Data;
RBTree<T> * m_Children[2];
RBTree<T> * m_Parent;
bool m_Color;
9
  • 2
    What compiler? Works for me with g++, clang and msvc. Commented Oct 14, 2015 at 5:24
  • 1
    It should work. Any context? Commented Oct 14, 2015 at 5:28
  • Please show the actual error message. Commented Oct 14, 2015 at 5:37
  • That's assignment, not initialization. There's a difference. Arrays don't support assignment. Commented Oct 14, 2015 at 5:42
  • I thought that because it's in the constructor it would be considered initialization. Is this wrong then? Commented Oct 14, 2015 at 5:43

2 Answers 2

1

The form T * myPtrArray[2] = {0, 0}; is called aggregate initialization. It has no counterpart in assignment, so writing

T * myPtrArray[2];
myPtrArray = {0, 0};

is invalid.

In the case of class construction, aggregate initialization is unavailable in c++98/03.

If your compiler supports c++11 standard, you can use uniform initialization syntax. There are two ways to initialize m_Children in your example:

#1

In constructor:

template <class T>
RBTree<T>::RBTree(): m_Children {0, 0} /* other init here */ {

}

#2

During class member declaration:

T m_Data;
RBTree<T> * m_Children[2] {0, 0};
RBTree<T> * m_Parent;
bool m_Color;
Sign up to request clarification or add additional context in comments.

2 Comments

#1 isn't supported pre-C++11. But m_children() is, and is probably the better option because ti does not depend on the number of elements in the array.
ITYM #2 isn't supported (during class member declaration).
0

As of C++11, you can use nullptr instead of 0. Using nullptr is preferred, as it is a pointer instead of an integer. Then, you could do:

T * myPtrArray[2] = {nullptr, nullptr};

Anyway, your code works fine on my compiler, you can see an example using both 0 and nullptr that compiles without errors on ideone.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.