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?
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;
}
通过使用“ cc -E main.c -o main.i”检查预处理器阶段的输出,并检查预处理器如何将宏转换为指令。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.