Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: Detecting Incomplete Array Initialization at Compile Time? |
| Date | 2016-07-21 12:42 -0700 |
| Organization | None to speak of |
| Message-ID | <lninvykcbj.fsf@kst-u.example.com> (permalink) |
| References | <58720375-dff5-4abf-9475-4080c0feb740@googlegroups.com> <nmr5cc$fkg$1@dont-email.me> |
Ken Brody <kenbrody@spamcop.net> writes:
> On 7/21/2016 2:39 PM, David T. Ashley wrote:
>> Found a bug related to incomplete array initialization yesterday. The form of the bug was:
>>
>> enum
>> {
>> Apples,
>> Oranges,
>> Grapefruits,
>> MaxElements
>> };
>>
>> int myarray[MaxElements] =
>> {
>> 429,
>> 258
>> //Oops, missing initializer--not intended.
>> //C-language defaults to 0.
>> };
>>
>> Question: Is there any way to detect incomplete initialization at compile-time? (Any obscure feature of the language I'm not aware of?)
>>
>> Caveat: I've oversimplified the problem for the purposes of example. Also, this occurred in an embedded system, and doing anything at runtime is off the table.
>>
>
> This might do what you want:
>
> enum
> {
> Apples,
> Oranges,
> Grapefruits,
> MaxElements
> };
>
> int myarray[] = /* Leave off the array size here. */
> {
> 429,
> 258
> //Oops, missing initializer--not intended.
> //C-language defaults to 0.
> };
>
> static char MyArraySizeCheck[ ( sizeof(myarray)/sizeof(myarray[0]) )
> == MaxEmements ? 1 : -1 ];
>
> If the size is "wrong", then the compiler will complain about the "-1" array
> size on "MyArraySizeCheck".
That's a hack to implement a static assert. (I'm not using the word
"hack" negatively.)
If you have C11 support, or a compiler that implements it as an
extension, you can just use static assert:
_Static_assert(sizeof myarray / sizeof myarray[0] == MaxElements,
"Extra or missing elements");
(I'd suggest using #if and #error, but sizeof can't be evaluated in
preprocessor expressions.)
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Detecting Incomplete Array Initialization at Compile Time? "David T. Ashley" <dashley@gmail.com> - 2016-07-21 11:39 -0700
Re: Detecting Incomplete Array Initialization at Compile Time? Ken Brody <kenbrody@spamcop.net> - 2016-07-21 14:47 -0400
Re: Detecting Incomplete Array Initialization at Compile Time? Keith Thompson <kst-u@mib.org> - 2016-07-21 12:42 -0700
Re: Detecting Incomplete Array Initialization at Compile Time? Tim Rentsch <txr@alumni.caltech.edu> - 2016-07-21 20:07 -0700
csiph-web