13

Generate a unique static symbol

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <malloc.h>
  4.  
  5. #define SYMB    "symb"      /* default symbol prefix */
  6.  
  7. char *gensym( char *s ) {
  8.     char buf[ 16 ];
  9.     unsigned l;
  10.     char *symb;
  11.  
  12.     static unsigned n = 0;
  13.  
  14.     if ( !s )
  15.         s = SYMB;
  16.     sprintf(buf, "%u", ++n);
  17.     l = strlen( s );
  18.  
  19.     symb = (char *)malloc(l + strlen(buf) + 1);
  20.     strcpy( symb, s );
  21.     strcpy( symb+l, buf );
  22.  
  23.     return symb;
  24. }
  25.  
  26. main() {
  27.     int i;
  28.     for ( i = 0; i < 10; i++ )
  29.         printf("%s\n", gensym( 0 ));
  30.     for ( i = 0; i < 10; i++ )
  31.         printf("%s\n", gensym( "foo" ));
  32. }
$ gcc -o gensym gensym.c
$ ./gensym
symb1
symb2
...
symb10
foo11
foo12
...
foo19
foo20

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].