How to strengthen arithmetic result in a preprocessor macro

How to write a macro that receives two arguments and (giving, for example, 3and 2) return the next output?

The sum of 3 and 2 is 5

Here is what I am writing, but it does not compile:

#define SOMMA(x, y) puts("La somma di " #x " e " #y " e' " #(x+y));

calling him

SOMMA (a, b);

with aand bentered before ...

+4
source share
2 answers

You can use printfinstead putsand do something similar.

#define SOMMA(x, y) printf("sum of %d and %d is %d\n", x, y, (x + y));

A note %daccepts only integer values, so you probably need a different macro for double / floats.

EDIT

As stated in rcgdlr, you can also use sprintfor snprintfif you want to create a string containing your result.

#define MAXLEN 256
#define SOMMA(x, y, res) snprintf(res, MAXLEN, "sum of %d and %d is %d\n", x, y, (x + y));

:

char buffer[MAXLEN];
SOMMA(4, 6, buffer);
printf("%s\n", buffer);
+3
#define SOMMA(x, y) printf("The Sum Of A = %d and B= %d is %d",a,b,(a+b))
0

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


All Articles