variable length array folded to constant array

9.9k views Asked by At
const int buf_length = 255;
char buf[ buf_length + 1 ];

snprintf(buf, buf_length, "%d Next on [%s] %s:", channel, station_channel(channel), station_name(channel));

strncat(buf, "(", buf_length - strlen (buf));
strncat(buf, station_country( xmltv ), buf_length - strlen(buf));
strncat(buf, ")", buf_length - strlen (buf));

country_list_set_text( buf );

This get warning:

variable length array folded to constant array as an extension.

Can you help to solve this?

2

There are 2 answers

0
Jonathan Leffler On BEST ANSWER

In C, a const int variable is a variable (that happens to be const-qualified), rather than an integer constant that is required when used in the bounds of global and static arrays, or in the case labels of a switch statement. See static const vs #define in C for an extensive discussion. I'm assuming that you are aware of what a VLA (variable length array) is — if not, comment and I'll add clarification.

There are a couple of ways around it. The one I normally use is an enum:

enum { buf_length = 255 };
char buf[buf_length + 1];

snprintf(buf, sizeof(buf), "%d Next on [%s] %s:",
         channel, station_channel(channel), station_name(channel));

Note that I changed the use of buf_length in the snprintf() call to sizeof(buf); that is the canonical way to do it when the array declaration is in scope — and avoids wasting the extra byte you added to the buffer.

You could use #define buf_length 255; that is the classic way to do it.

I would often use an upper-case constant (BUF_LENGTH) rather than lower-case to designate a constant. It isn't actually critical, but it is more or less conventional in C (witness the majority of the constants in the C standard, with oddball exceptions such as L_tmpnam).

In C++, the story is different. The const int buf_length = 255; can be used in switch statements and array bounds.

0
Sergey Kalinichenko On

The buf_length + 1 is not treated as a compile-time constant expression.

Replacing the second declaration with

char buf[256];

should fix the problem.

You may want to replace buf_length with a #define:

#define BUF_LENGTH 255
char buf[BUF_LENGTH + 1];