0

Is it possible to write a macro such as the following:

putcharX(repeat, char)

==>

putcharX(5, '*');

==>

putchar('*');
putchar('*');
putchar('*');
putchar('*');
putchar('*');

Note: I'm not looking to use a for/while/do loop, but literally copy the command n number of times in the code. Is such a thing possible with the cpp?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 3
    This is literally why for loops exist. And at high optimization levels the compiler will unroll the loop for you, which means it will copy the contents 5 times, if that makes any sense for the program. This question is such an obvious "Why would you want to do it?" kind of thing. – Zan Lynx Feb 16 '21 at 23:43
  • 1
    Anyway, no. You cannot do this with a number. You could create a set of macros named `REPEAT2`, `REPEAT3` etc and do it that way. – Zan Lynx Feb 16 '21 at 23:44
  • @ZanLynx well, an example would be like using `strace` -- measuring how long something takes on my computer, so running `putchar` 10M times or so and seeing what the average time it takes. A loop would add at least two instructions for the `jmp` and `update` expression, wouldn't it? Example here: https://godbolt.org/z/f5nbjb. – samuelbrody1249 Feb 16 '21 at 23:53
  • 3
    Possible with a set of macros : `putcharX(N, CH);` selectively calls `putcharX_256` with in turn calls `putcharX_128` which calls `putcharX_64` ..... A tad ugly, but doable. – chux - Reinstate Monica Feb 16 '21 at 23:53
  • @chux-ReinstateMonica yes, exactly. That was what I was looking for, thank you. – samuelbrody1249 Feb 16 '21 at 23:54
  • @samuelbrody1249 No time to code it right now, but with 8 levels of nesting , makes for a _long_ code to compiler . May break the compiler if the upper bound of N is large. – chux - Reinstate Monica Feb 17 '21 at 00:02
  • 1
    @samuelbrody1249 If you're trying to benchmark CPU instructions you're better off using assembly. Also if the CPU is anything near modern it is almost a waste of time. Compare and branch instructions will fuse together invisibly and be predicted hundreds of cycles in advance. They become essentially free. Also if you created a program that was literally 10M putchar calls in a row the CPU instruction cache would become useless and you're measuring RAM bandwidth. – Zan Lynx Feb 17 '21 at 00:50

1 Answers1

2

you cannot write "real" recursive statements in macros. the closest you can get is

#define putcharOne putchar('*')
#define putcharTwo putcharOne; putcharOne
#define putcharThree putcharOne; putcharOne; putcharOne


#include <stdio.h>



int main()
{
        putcharOne;
        putcharTwo;

return 0;
}
theCreator
  • 166
  • 4