0

I have two pointer variables (prevGuiMsg and currGuiMsg) to a struct inside another struct definition in a C++ source-file:

typedef struct
{
    bool re_pop_required;
    bool concurrent_popups;
    MlGuiMsg* prevGuiMsg;
    MlGuiMsg* currGuiMsg;
    uint32_t first_popup;
    uint32_t second_popup;
}RePopup;

The M1GuiMsg-struct is defined inside a different C header-file (I'm mixing C and C++ code). A pointer to the struct is passed as an argument to a function in the source file, where I wish to store the data that the parameter points to in the pointer variables prevGuiMsg and currGuiMsg.

I wish to explicitly declare a variable of the type struct RePopup and initialize its members along with the declaration in the C++ source file:

RePopup rp = {false, false, 0, 0, 0, 0};

My question is therefore: can/should one initialize a pointer to a struct with zero inside the explicit declaration of another struct?

0

1 Answer 1

3

You should use nullptr rather than 0 but otherwise there is nothing wrong with initialising a pointer to 0.

Sign up to request clarification or add additional context in comments.

6 Comments

What is the advantage of using nullptr rather than 0?
If he's using C++11 or newer, yes.
@AbdelAleem It wouldn't make a technical difference for directly initializing a pointer member like this, but it can make a difference in some cases involving overloaded functions and/or templates. So it's a good practice to use it by default for all pointers, and it also makes the intent of the code clearer.
It means you are being explicit that you are null initialising a pointer. Also you will get an error if you accidentally try to assign nullptr to an integer. e.g. if you mistyped your initialiser as {false, false, 0, nullptr, nullptr, 0} it wont compile
@AbdelAleem Self-documentingness only in this particular case, but it's a good habit generally.
|

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.