Originally Posted by
jimblumberg
Hopefully you are compiling with a standard C11 compatible compiler, any previous version doesn't have the "_STDC_NO_VLA_" macro.
Also the "_STDC_NO_VLA_" macro by it's self doesn't control the use of VLA, it only tells you if VLA is a supported feature.
The -Wvla flag should issue diagnostics if you attempt to use this "feature" regardless of the setting of the _STDC_NO_VLA_ macro. By the way this diagnostic can be either a warning or an error, depending on what other flags you use to compile you code.
Is there a reason you're trying to support this "feature"? Since VLA are not supported by all compilers , remember VLA support is optional, you would probably be better off sticking with the tried and true dynamic memory allocation instead.
Thanks for your explanation. There isn't a particular reason, it is nothing more than a syntatic sugar, but I want to make it working.
I would like to be able to write code suitable for any version of the C standard (from C90 to C11): using the preprocessor i would check VLA support, so that the code using pointers-to-VLA would be compiled only if the compiler is able to support them. But I have to take care to any flag that prevents me from using them.
How can I achieve all these goals?
I'm going to post my code right now so you can see what I'm doing. It's hard to find code like this, but it is simple enough.
Code:
#include <stdio.h>
#include <stdlib.h>
#ifdef __STDC_NO_VLA__
#error Your compiler does not support VLAs! Please use a supported compiler.
#endif
void getDimensions(unsigned *, unsigned *);
unsigned (*allocate(unsigned, unsigned))[];
void doSomething(unsigned, unsigned, unsigned(*)[*]);
int main()
{
unsigned r, c;
getDimensions(&r, &c);
unsigned(*matrix)[c] = (unsigned(*)[c]) allocate(r, c);
if(matrix)
doSomething(r, c, matrix);
free(matrix);
return 0;
}
void getDimensions(unsigned *r, unsigned *c) {
do {
scanf("%u", r);
scanf("%u", c);
} while(*r == 0 || *c == 0); // unsigned -> negative values in input will be considered positive
return;
}
unsigned (*allocate(unsigned r, unsigned c))[]
{
return (unsigned(*)[]) malloc(r * c * sizeof(unsigned));
}
void doSomething(unsigned r, unsigned c, unsigned(*matrix)[c]) {
unsigned i = 0;
unsigned j;
for(; i < r; i++)
for(j = 0; j < c; j++)
matrix[i][j] = j * i;
for(i = 0; i < r; printf("%c", '\n'), i++)
for(j = 0; j < c; j++)
printf("%u ", matrix[i][j]);
return;
}