How to write macros in c++?

Hello,

I was wondering how I can write macros like in blueprints but in c++?

Thanks in advance :slight_smile:
~Stefan

Macros in C++ may sometimes be a bit tricky so be careful. You start it with #define directive.

#define macro-name replacement-text

Example:

#define PI 3.14159

Macros in C++ are used by preprocessor (stage before compilation and linking). In the example above it will simply replace all PI occurrences in code with 3.14159 number.

Macros can be more complex:

#define MIN(a,b) (((a)<(b)) ? a : b)

Example of usage:

std::cout << "The minimum is " << MIN(42, 8) << endl;

will result in:

The minimum is 8

Experienced C++ developers will suggest you to not use macros as long as possible. Functions and variables are most times a better choice. For example const float pi = 3.14159; is better than #define because it handles type and compiler can help you more when you will try to do something wrong with it.

More information:

https://en.cppreference.com/w/cpp/preprocessor

https://en.cppreference.com/w/cpp/preprocessor/replace

This is not what I meant. I’m trying to define a function in c++ that when used in blueprints can have more than 1 input/output. For example like the branch node in bps that have 2 outputs, “true” and “false”.

You need to create a function with an enum parameter from uint8 passed by reference.

The code is the following :

.h file

UENUM(BlueprintType)
enum class EMyBranchEnum : uint8
{
    FirstBranchName,
    SecondBranchName
};

// Blueprint library class declaration...
UFUNCTION(BlueprintCallable, meta=(ExpandEnumAsExecs = Branch))
void SomeBranchFunction(const int & Param1, EMyBranchEnum& Branch);

.cpp file

void UMyBlueprintLib::SomeBranchFunction(const int & Param1, EMyBranchEnum& Branch)
{
    if (Param1 > 12)
    {
        // Tell to call first branch node
        Branch = EMyBranchEnum::FirstBranchName;
    }
    else
    {
        // Tell to call second branch node
        Branch = EMyBranchEnum::SecondBranchName;
    }
}

By expanding the enum, you can use a maximum of 255 branches.