Is the definition of the variable name in the #define directive correct?

If I had the following code:

#include <stdio.h>
#define VAR_NAME a_variable

int VAR_NAME = 42;

int main()
{
    printf("%i\n", VAR_NAME);
    printf("%i\n", a_variable);
    a_variable = 123;
    printf("%i\n", VAR_NAME);
    printf("%i\n", a_variable);

    return 0;
}

      

Is the definition a_variable

correct? On my system, I announced int

with the name a_variable

, but I need to worry about alternative compilers, announcing int

the name VAR_NAME

?

BTW, the above code outputs the following:

42
42
123
123

      

EDIT:

Also, if the previous one is clearly defined, can I do the following?

#define VAR_NAME a_variable
...
#define DECL_VAR int VAR_NAME

// Declare an int named a_variable
DECL_VAR;

      

+3


source to share


2 answers


Do I need to worry about alternative compilers declaring int

with a name VAR_NAME

?

No, you have nothing to worry about. Unless someone overrides VAR_NAME

something else, you get consistently int

named a_variable

.

#define

the directive is processed by the preprocessor before the compiler processes the code. By the time the compiler "sees" your code, it is not there VAR_NAME

, only it a_variable

remains in all places where it was used VAR_NAME

.



Also, if the previous one is clearly defined, can I do the following?

#define DECL_VAR int VAR_NAME

      

Yes, if VAR_NAME

defined, this will work as well.

Note. The fact that it is well defined and standardized does not mean that it is imperative to use such code, because the cascading declarations are difficult to read for the readers of your program.

+8


source


Assuming the implementation conforms to the standard, the preprocessor will perform text substitution, so each instance VAR_NAME

will be expanded to a_variable

.

There are a few exceptions (for example, macros inside string literals are not expanded). But if you use the macro in places where a variable name is usually expected, the extension will work as you expect.

It is also necessary to avoid reserved identifiers (identifiers that standard reserves are used for implementation, i.e. compiler and standard headers). For example, if you choose a name for your macro or for a reserved variable (for example, it starts with an underscore followed by an uppercase letter, for example _VAR_NAME

, not VAR_NAME

), then the behavior is undefined.



EDIT after editing the original question: Yes, the extension DECL_VAR

works as you expect.

I would warn you about this. Such tricks do not bring many benefits, but they can make your code harder to understand (after all, few people know what DECL_VAR;

will mean in your code if they do not know that you are playing with macros). Code that is harder to understand is harder to understand.

+4


source







All Articles