How do I initialize an array inside a struct without making each element separate? (C ++)

My questions are in code, but basically I want to know how / if I can make two commented lines? I know I can do this in the constructor, but I don't want to!

struct foo
{
    int b[4];
} boo;

//boo.b[] = {7, 6, 5, 4}; // <- why doesn't this work? (syntax error : ']')
//boo.b = {7, 6, 5, 4}; // <- or else this? (syntax error : '{')

boo.b[0] = 7; // <- doing it this way is annoying
boo.b[1] = 6; // :
boo.b[2] = 5; // :
boo.b[3] = 4; // <- doing it this way is annoying

boo.b[4] = 3; // <- why does this work!

      

(Usage: C ++, Visual Studio 2005.)

+2


a source to share


4 answers


You can only use initialization in the definition:

struct foo
{
    int b[4];
};
foo boo = { 7, 6, 5, 4 };

      

In the last question: "Why does it work boo.b[4] = 3

?" The answer is that this behavior is undefined and UB allows quite a few different situations. Neither the compiler nor the runtime should diagnose it, and in many cases the result will overwrite the next item in memory. This can be tested with the following code:



// Test
foo boo;
int x = 0;
boo.b[4] = 5;
std::cout << x << std::endl;

      

NOTE. This behavior is undefined, so regardless of the test result, it is incorrect and cannot be considered a repeatable test.

+8


a source


struct foo
{
    int b[4];
} boo = {7,6,5,4};

      



+2


a source


If you need to write to this struct member after initializing it, it looks like your values ​​follow the simplest pattern (starting at 7 and decrementing by one), which means that std::generate()

or std::generate_n()

might do the job too:

#include <algorithm>
class DecrementFrom {
        int val;
public:
        DecrementFrom(int start) : val(start) {}
        int operator()() { return val--; }
};

std::generate_n(foo.b, 4, DecrementFrom(7));

      

+1


a source


Strictly speaking, the syntax for initializing an array inside a structure is:

struct foo 
{ 
    int b[4]; 
}; 
foo boo = { { 7, 6, 5, 4 } };

      

However, according to 6.7.8.17 of the C standard, the compiler will implicitly keep track of the corresponding scope if you don't provide it.

+1


a source







All Articles