Search code examples
c++macrosconstantsnew-operatordynamic-memory-allocation

Can I specify the elements of a dynamically allocated array with a macro constant by using new?


I know it does not make much sense since one of the purposes to choose the allocation on the heap is to provide the number of elements by a variable object but can I specify the number of elements of an dynamically allocated array with a macro constant?

Like, f.e.:

int* ptr = new int[SIZE];

with the macro constant of SIZE:

#define SIZE 25

I´ve already tested it with g++ and the compiler has passed it without an error or a warning. But that does not mean that it caused no issues or maybe is Undefined Behavior.

  • Can I specify the elements of a dynamically allocated array with a macro constant in C++?

Solution

  • Can I specify the elements of a dynamically allocated array with a macro constant in C++?

    Short answer: Yes!

    Reason: Macros that are specified with the #define directive are evaluated, and replaced by the evaluated values, by the pre-processor - that is, before the actual compiler gets to work on the code. Thus, given your (previous) #define SIZE 25 line, the code:

    int* ptr = new int[SIZE];
    

    will, to the compiler, be exactly equivalent to:

    int* ptr = new int[25];
    

    In fact, such usage of macros is quite common - for example, in code that has to be built for different platforms, where the value of SIZE would vary between such builds. For example, one could conditionally define SIZE as follows:

    #ifdef PLATFORM25
    #define SIZE 25
    #else
    #define SIZE 50
    #endif
    

    Or, one could even define the SIZE macro with a compiler command-line option - a switch something like (depending on the compiler):

    /DSIZE=25