This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Using C preprocessor to limit array size during compilation

Hello,

I want to use the #error directive to limit the size of a statically allocated array during compilation (it must not exceed a certain limit, and I want to fail compilation, not startup, if it is too large), but I can only work with constant expressions, of course. Is there a way to do this...?

Thanks.

Parents
  • Maybe something like this is what you want:

    ... some declaration of my_array ...
    
    #define MAX_SIZE 5000 /* bytes, for example */
    
    typedef int dummy[sizeof(my_array) <= MAX_SIZE ? 1 : -1];
    

    If the size of the array is small enough this will create a legal typedef named dummy that we don't actually use.

    If the size is too big then the typedef is illegal an the compiler should give an error.

    Some compilers/mode allow zero length arrays, but I haven't met one that allows -1 length arrays.

Reply
  • Maybe something like this is what you want:

    ... some declaration of my_array ...
    
    #define MAX_SIZE 5000 /* bytes, for example */
    
    typedef int dummy[sizeof(my_array) <= MAX_SIZE ? 1 : -1];
    

    If the size of the array is small enough this will create a legal typedef named dummy that we don't actually use.

    If the size is too big then the typedef is illegal an the compiler should give an error.

    Some compilers/mode allow zero length arrays, but I haven't met one that allows -1 length arrays.

Children
No data