Is there a C macro to generate repeat string? [dup

2020-02-12 07:54发布

问题:

Suppose I want to generate ------, with only -, is there a C macro to generate repeated string ?

回答1:

use boost, E.g

#include <stdio.h>
#include <boost/preprocessor/repetition/repeat.hpp>

#define Fold(z, n, text)  text

#define STRREP(str, n) BOOST_PP_REPEAT(n, Fold, str)

int main(){
    printf("%s\n", STRREP("-", 6));
    return 0;
}


回答2:

Yes and no. It's not simple, and not generally a good idea, but you can do it for finite, constant sizes, and for constant characters. There are many ways to do this with the C preprocessor. Here is one:

#define DUP(n,c) DUP ## n ( c )

#define DUP7(c) c c c c c c c
#define DUP6(c) c c c c c c
#define DUP5(c) c c c c c
#define DUP4(c) c c c c
#define DUP3(c) c c c
#define DUP2(c) c c
#define DUP1(c) c

#include <stdio.h>

int main(int argc, char** argv)
{
  printf("%s\n", DUP(5,"-"));
  printf("%s\n", DUP(7,"-"));
  return 0;
}

It's not pretty, and only useful when you really want the string to be stored as static (constant) data. Both the n and 'c' parameters to DUP have to be a constants (they cannot be variables). The Boost.Preprocessor module has a lot of good information for how and when to (ab)use the C/C++ preprocessor like this. Although Boost is a C++ library, the preprocessor information is largely applicable to straight C.

In general, you're much better off doing this in normal C code:

/* In C99 (or C++) you could declare this: 
     static inline char* dupchar(int c, int n)
   in the hopes that the compiler will inline. C89 does not support inline
   functions, although many compilers offered (inconsistent) extensions for
   inlining. */
char* dupchar(int c, int n)
{
  int i;
  char* s;

  s = malloc(n + 1); /* need +1 for null character to terminate string */
  if (s != NULL) {
    for(i=0; i < n; i++) s[i] = c;
  }
  return s;
}

or, use memset, as @Jack suggested.



回答3:

Not in C standard.You need to write your own implementation.

EDIT:

something like this:

#include <stdio.h>
#include <string.h>

#define REPEAT(buf, size, ch) memset(&buf, ch, size)

int main(void)
{

  char str[10] = { 0 };
  REPEAT(str, 9, '-');
  printf("%s\n", str); //---------

  return 0;
}