JSRK
JSRK

Reputation: 71

If #define is used without any assignment value, what will it do?

#define TML_ID - No value is assigned to TML_ID. There's no problem in compilation or building executables. will this assign any default value like null to TML_ID or will TML_ID be considered undefined ?

Upvotes: 7

Views: 5571

Answers (4)

Pete Becker
Pete Becker

Reputation: 76235

#define MACRO

defines a macro named MACRO. It has no content, so if you wrote something like std::cout << MACRO you'd get an error because there's nothing there. This is often used to conditionally use new keywords:

#if CPP_VERSION_C11
    #define NOEXCEPT noexcept
#else
    #define NOEXCEPT
#endif

void f() NOEXCEPT {
    // whatever
}

There are two other ways you can use such a macro. You can check whether it's defined:

#ifdef MACRO
    // code for one branch
#else
    // code for other branch
#endif

For that code, since MACRO has been defined, the preprocessor will look at the code in the first branch, and skip the code in the second branch. If MACRO had not been defined, it would skip the code in the first branch rather than the second. You can also do the same thing this way:

#if defined(MACRO)

or you can use it in a constant expression in a preprocessor directive:

#if MACRO
    // code for one branch
#else
    // code for other branch
#endif

here, MACRO gets the value 0, the #if sees the value 0, and the preprocessor skips the first branch. The same thing occurs in more complex expressions:

#if MACRO + 1 > 0
    // code for one branch
#else
    // code for other branch
#endif

Here, MACRO has the value 0, MACRO + 1 has the value 1, and the first branch will be selected.

Upvotes: 0

dusan.stanivukovic
dusan.stanivukovic

Reputation: 43

Without assigned a value, macros in this way are usually used to prevent including same .h file multiple times, this way:

#ifndef _FILENAME
#define _FILENAME

//declaration code

#endif

If some .cpp file includes, for example, two different .h files, which both include our .h file, then .cpp will have only one copy of declaration code, since second time _FILENAME macro will be DEFINED, and declaration code will be skipped.

Upvotes: 1

Sam
Sam

Reputation: 71

#define doesn't assign a value to the macro. In fact, it's considered as a flag to tell the compiler that a specific macro has been defined.

You can imagine it as if you declare a variable without assigning any values. It will have a garbage value but it will reserve a space in the memory. But in case of a macro, the definition won't reserve a space. Only a hint for the compiler.

Upvotes: 1

ForceBru
ForceBru

Reputation: 44828

This simply says that the macros is defined, so you can do this in main or any other function:

#ifdef TML_ID
printf("Defined!\n");
#else
printf("Undefined!\n");
#endif

Upvotes: 7

Related Questions