Gernot Frisch said:
>
"Richard Heathfield" <in*****@invalid.invalidschrieb im Newsbeitrag
news:Bd********************@bt.com...
<snip>
>>
Yes, but he specifically asked about the preprocessor. [...]
Very nice. So - can somone please show me how to check for max
stringlength at _compile time_?
Oh, okay. Let's take your original example:
#define CRYPT(a) \
#if sizeof(a)/sizeof(a[0]) 31 \
xCRYPT(a) \
#else\
#error xy\
#endif
Now let me just hack that to give a useful name that doesn't look silly when
quoted in ordinary text:
#define CRYPT(Array) \
#if sizeof(Array)/sizeof(Array[0]) 31 \
xCRYPT(Array) \
#else\
#error xy\
#endif
What we want, then, is a compile-time error if the size of Array exceeds 31.
Here's how:
char Array[SUSPECT_LENGTH] = {0};
char Error_ArrayIsTooLong[((sizeof Array / sizeof Array[0] <= OKAY_LENGTH) *
2) - 1] = {0};
With OKAY_LENGTH set at 31 and SUSPECT_LENGTH at 31, I get:
gcc -W -Wall -ansi -pedantic -Wformat-nonliteral -Wcast-align
-Wpointer-arith -Wbad-function-cast -Wmissing-prototypes
-Wstrict-prototypes -Wmissing-declarations -Winline -Wundef
-Wnested-externs -Wcast-qual -Wshadow -Wconversion -Wwrite-strings
-Wno-conversion -ffloat-store -O2 -g -pg -c -o foo.o foo.c
foo.c: In function `main':
foo.c:9: warning: unused variable `Error_ArrayIsTooLong'
With OKAY_LENGTH set at 31 and SUSPECT_LENGTH at 32, I get:
gcc -W -Wall -ansi -pedantic -Wformat-nonliteral -Wcast-align
-Wpointer-arith -Wbad-function-cast -Wmissing-prototypes
-Wstrict-prototypes -Wmissing-declarations -Winline -Wundef
-Wnested-externs -Wcast-qual -Wshadow -Wconversion -Wwrite-strings
-Wno-conversion -ffloat-store -O2 -g -pg -c -o foo.o foo.c
foo.c: In function `main':
foo.c:9: size of array `Error_ArrayIsTooLong' is negative
foo.c:9: warning: unused variable `Error_ArrayIsTooLong'
make: *** [foo.o] Error 1
QED.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)