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.