Are the following array declarations valid, if not why?: "i'm confused!"
const int SIZE=4;
void main()
{
int a= {0,2,4,6};
static int b={0,2,4,6,8};
int x[SIZE-5];
int d[SIZE*2];
. . .
. . .
}

Dani AI

Generated

Quick clarification of the issues in the original snippet and practical, modern fixes.

The line that tries to give multiple brace-enclosed values to a plain integer is invalid: a scalar cannot be initialized with a multi-element braced list. was pointing toward using an array instead; in modern C++ prefer a fixed-size container with a true compile-time size. For example, use a constexpr size and a wrapper that enforces the size at compile time:

#include <array>

constexpr int N = 4;
std::array<int, N> nums = {0, 2, 4, 6};

This avoids ambiguous scalar/aggregate rules and is portable.

Static and initializer-list behavior needs care. A scalar declared static still cannot accept multiple initializers. If a static array is declared with fewer initializers than its size, the remaining elements are zero-initialized; if there are more initializers than the declared size, that is a compile error. As noted, mismatching intended sizes (e.g., wanting 4 elements but providing 5) is an error — either change the declared size or let the compiler deduce it when appropriate.

Array bounds must be compile-time constant expressions in standard C++. A negative or zero-length dimension is not valid (zero-length is not standard; some compilers allow it as an extension). Modern guidance: use constexpr for compile-time sizes and static_assert to guard invariants, and use std::vector when the size must be determined at runtime. Also follow the standard signature for main (e.g., int main()), as recommended. As hinted, avoid preprocessor #define for sizes in C++; prefer constexpr (or const when appropriate) for clearer, safer code.

Recommended Answers

All 3 Replies

>>static int b={0,2,4,6,8};
SIZE = 4; b has 5 elements - not good

>>int x[SIZE-5];
SIZE-5 = -1. You cannot declare an array with negative dimention.

Also, int main () , not void main ().
And, for defining the size of an array, I prefer #define SIZE X instead const int SIZE=X,

#define is old C style syntax, in C++ const is preferred.

Are the following array declarations valid, if not why?: "i'm confused!"
const int SIZE=4;
void main()
{
int a= {0,2,4,6}; ---------------(1)
static int b={0,2,4,6,8};
int x[SIZE-5];
int d[SIZE*2];
. . .
. . .
}

You can re-write the statement (1) as follows:
int a[] = {0,2,4,6};
void main()
{

...

}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.