0

Just trying to print the square of a number using macros. Self explanatory C program :

#include <stdio.h>
#define  numb(a)  \
   printf(#a * #a)

int main(void) {
   int num;
   printf("Enter a num: ");
   scanf("%d",&num);
   numb(num);
   return 0;
}

Getting the error :

main.c: In function ‘main’:
main.c:4:14: error: invalid operands to binary * (have ‘char *’ and ‘char *’)
    printf(#a * #a)
              ^
main.c:10:14:
    square(num);
              ~
main.c:10:4: note: in expansion of macro ‘square’
    square(num);
    ^~~~~~

How can I convert that char to int to sucessfully use the binary operator?

  • 3
    You’re going to have to end up at `printf("%d", num * num)` somehow, macros or not. Understand that macros operate on bits of C source code at compile time, so `#a` is `"num"`. – Ry- Aug 17 '18 at 04:14
  • 2
    It's not possible to stringize the result of arithmetic, via the preprocessor. You may find the compiler optimizes it though, e.g. it could convert `printf("%d", 5*5);` to `printf("25");` – M.M Aug 17 '18 at 04:22
  • `square(1+2)` returns on my machine `5` while I would expect `9`. – unalignedmemoryaccess Aug 17 '18 at 04:42
  • Possible duplicate of [What does #x inside a C macro mean?](https://stackoverflow.com/questions/14351971/what-does-x-inside-a-c-macro-mean) – phuclv Aug 17 '18 at 05:00
  • 1
    \@Maccen your macro was named `numb` but in the error message it's `square`? @tilz0R if you renamed `numb` to `square` then you'll get `printf("1+2" * "1+2")` in this case – phuclv Aug 17 '18 at 05:09
  • I would suggest better to use the function to do such kind of things. If you're just learning how to use the function like macro() is fine. Imagine in production code if someone sends in the `num` as `num++` then it's undefined behaviour. – danglingpointer Aug 17 '18 at 06:57

2 Answers2

4

Your macro needs to be c code so just ditch the # and write the formatting string for an integer

#include <stdio.h>
#define  square(a)  \
   printf("%d", (a) * (a))

int main(void) {
   int num;
   printf("Enter a num: ");
   scanf("%d",&num);
   square(num);
   return 0;
}
Andre Motta
  • 759
  • 3
  • 16
-1

check the output of preprocessor stage by using "cc -E main.c -o main.i" and check how the preprocessor converting macros to instruction .

new_learner
  • 131
  • 10