The compiler sends me a folding constant warning about the following code snippet:


// Text button constants
// =========================
const uint8_t TEXT_BUTTON_HEIGHT            = 25;
const uint8_t TEXT_BUTTON_MAX_TEXT_LEN      = 30;

// This pads text and toggle switches within buttons.
const uint8_t TEXT_BUTTON_CONTENT_PADDING   = 10;

const uint8_t TEXT_BUTTON_LEFT_MARGIN_TEXT  =  1;
const uint8_t TEXT_BUTTON_CENTER_TEXT       =  2;
// ==========================

typedef struct
  char text[TEXT_BUTTON_MAX_TEXT_LEN + 1];    // This is the problem line
  // This should be one of the following:
  uint8_t text_horiz_pos;

  uint8_t text_color;
  uint8_t button_color;
  uint24_t button_width;
} text_button_t;

The file name is gui.h. It provides function definitions and constants for implementation file, gui.c. The precise wording of the compiler error is:

src/gui.h:43:14: warning: variable length array folded to constant array as an extension [-Wgnu-folding-constant]
  char text[TEXT_BUTTON_MAX_TEXT_LEN + 1];

I need the TEXT_BUTTON_MAX_TEXT_LEN to be a constant since I use it in the implementation file. The "plus 1" in the array declaration tacks on room for the null terminator.

I didn't find anything about how to fix this warning on DuckDuckGo. What should I do to fix/silence this warning?
When you specify the size of a C array as a non-constant expression, it becomes a VLA which has different semantics from normal arrays. Here the compiler is warning you that it happens to know the size of the array at compile time even though it's a non-constant expression, and so it's using normal array semantics instead of VLA semantics. In C++ that would indeed be a constant expression, but in C it isn't. You can either use defines or enums for the constants in order for it to be a C constant expression. For example:
enum { TEXT_BUTTON_HEIGHT = 25 };
Enums are often preferred over defines, for the most part just because debuggers understand them better.
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum