C # define macros

This is what I have, and I wonder how it works and what it actually does.

#define NUM 5
#define FTIMES(x)(x*5)

int main(void) {
    int j = 1;
    printf("%d %d\n", FTIMES(j+5), FTIMES((j+5)));
}

It produces two integers: 26 and 30.

How to do it?

+3
source share
7 answers

The reason for this is because your macro extends printing to:

printf("%d %d\n", j+5*5, (j+5)*5);

Value:

1+5*5 and (1+5)*5
+17
source

Since it has not been mentioned yet, a way to fix this problem is to do the following:

#define FTIMES(x) ((x)*5)

The braces around xin the macro extension prevent operator associativity.

+12
source

define - .

- :

FTIMES (j + 5) = 1 + 5 * 5 = 26

FTIMES ((j + 5)) = (1 + 5) * 5 = 30

+3

FTIMES , , . , , , :

#define NUM 5
#define FTIMES(x)(x*5)

int main(void)
{

    int j = 1;

    printf("%d %d\n", j+5*5,(j+5)*5);
}

, , , 26 30.

+2

:

#define FTIMES(x) ((x) * 5)
+1

NUM ocurrences 5, FTIMES (x) x * 5. .

.

0

.

FTIMES (j + 5), j = 1:

1 + 5 * 5

:

25 + 1

= 26

FTIMES ((j + 5)), :

(1 + 5) * 5

6 * 5

30

0

Source: https://habr.com/ru/post/1702259/


All Articles