13
Générer un nom de variable unique
- #include <stdio.h>
- #include <string.h>
- #include <malloc.h>
- #define SYMB "symb" /* default symbol prefix */
- char *gensym( char *s ) {
- char buf[ 16 ];
- unsigned l;
- char *symb;
- static unsigned n = 0;
- if ( !s )
- s = SYMB;
- sprintf(buf, "%u", ++n);
- l = strlen( s );
- symb = (char *)malloc(l + strlen(buf) + 1);
- strcpy( symb, s );
- strcpy( symb+l, buf );
- return symb;
- }
- main() {
- int i;
- for ( i = 0; i < 10; i++ )
- printf("%s\n", gensym( 0 ));
- for ( i = 0; i < 10; i++ )
- printf("%s\n", gensym( "foo" ));
- }
$ gcc -o gensym gensym.c
$ ./gensym
symb1
symb2
...
symb10
foo11
foo12
...
foo19
foo20
Commentaires