tags:

views:

412

answers:

6

I have a struct:

struct something {
    int a, b, c, d;
};

Is there some easy way to set all those a,b,c,d into some value without needing to type them separately:

something var = {-1,-1,-1,-1};

Theres still too much repetition (lets imagine the struct has 30 members...)

I've heard of "constructs" or something, but i want to set those values into something else in different part of the code.

+5  A: 

You can define a method for the struct. So why not:

struct something {
    int a, b, c, d;

    void set_values(int val) 
    { 
      a = b = c = d = val;
    }
};

something foo;

foo.set_values(-1);

Its definitely worth mentioning the point @sbi raised in the comments: if you're intent is to initialize the struct, then you should do so with a constructor. You should avoid allowing users of your structs/object to put it in an unusable/error state.

Alan
How is that not typing them separately? Having `init` take one argument would work
Michael Mrozek
Yeah sorry, I edited it, when I reread his question.
Alan
I think, in this case, it would be more clearly expressed as: a = b = c = d = val;
Ferruccio
if you downvote, please leave a comment why.
Alan
@Alan: As for me, I down-vote this because member functions initializing a type should be __constructors__. What you have there is two-phase construction, which is as bad as initialization gets. (If we'd be able to always successfully deal with two-phase construction, a certain Dane wouldn't have needed come up with a new language that featured constructors.)
sbi
@sbi: I agree with you. However my example isn't a complete one. The idea of a constructor is that an object (or struct) should be 100% usable as soon as it can be instantiated. As you aptly put, if you have to call a 2nd method to initialize an object after construction, you give room for a lot of error. However, there is nothing stopping you from calling an initialization method inside your constructor. Consider the case where you want to use an object pool. An initialize(or reinitialize) method make sense, and doesn't rely on compilers supporting RVO.
Alan
@Alan: A considerable point, but none made in the answer I voted on.
sbi
@sbi: the original question asked by the OP is ambiguous to his motives. It wasn't clear that he was asking for a way to initialize the struct, instead he was asking for a way to set all the values in a struct, not just at construction time. I'm not intimately familiar with RVO and how it relates to the spec, but I assume it's not required, so using an explicit method to set all values (much like a setter) seems the most straightforward approach. I'm not asking to rescind the -1, just want to make it clear that I don't advocate a 2-step object initialization approach :)
Alan
@Alan: But what about memset? Wouldn't that be the most efficient approach?
0A0D
+8  A: 

Simply give the struct a constructor:

struct something {
    int a, b, c, d;
    something() {
        a = b = c = d = -1;
    }
};

and then use it:

int main() {
   something s;    // all members will  be set to -1
}

you can also use the constructor to reset members:

int main() {
   something s;    // all members will  be set to -1
   s.a = 42;   
   s = something();  // reset everything back to -1
}
anon
Wouldn't memset do the same thing? I guess it would loose its OOness and be more C-like if you did a memset instead.
0A0D
memset works on chars, not on objects of a size different from char. While it works for 0 and -1(at least on x86, i would not bet on it on different plattforms), it will result in wrong assignments if the initialization value get changed. For example, `int i; memset(` will store sizeof(int) 1's into i, which is 0x01010101 on an 32bit machine.
Rudi
@Rudi: Yes, you are right. I was taking the OP's example literal in meaning that he wants to set all values to -1.
0A0D
+12  A: 

This is my second answer for this question. The first did as you asked, but as the other commentors pointed out, it's not the proper way to do things and can get you into trouble down the line if you're not careful. Instead, here's how to write some useful constructors for your struct:

struct something {
    int a, b, c, d;

    // This constructor does no initialization.
    something() { }

    // This constructor initializes the four variables individually.
    something(int a, int b, int c, int d) 
        : a(a), b(b), c(c), d(d) { }

    // This constructor initializes all four variables to the same value
    something(int i) : a(i), b(i), c(i), d(i) { }

//  // More concise, but more haphazard way of setting all fields to i.
//  something(int i) {
//      // This assumes that a-d are all of the same type and all in order
//      std::fill(&a, &d+1, i);
//  }

};

// uninitialized struct
something var1;

// individually set the values
something var2(1, 2, 3, 4);

// set all values to -1
something var3(-1);
Gunslinger47
+1  A: 

As i gathered, you want your struct to stay a POD but still want to have some "convenience constructor".
Adding a constructor to it wouldn't work in this case as you'd lose the POD-ness, thus i'd use a helper function:

something make_something() {
    something s = { -1, -1, -1, -1};
    return s;
}

If you want to set it to varying values, let the function take a, maybe optional, parameter:

something make_something(int i = 0) {
     something s = { i, i, i, i };
     return s;
} 

Now you can get the definition and initialization down to one line:

something s = make_something(-1);
Georg Fritzsche
Does this function differ anyhow from the Alan's answer where the function is inside the struct? I dont see a point creating external function, when it still (probably) works only with the one struct.
Newbie
@Newbie: The only notable difference is that you need more statements with his solution: `something s; s.set_values(-1);` vs. `something s = make_something(-1);`. When directly passing as arguments it becomes more apparent: `something s; s.set_values(-1); some_func(s);` vs. `some_func(make_something(-1));`.
Georg Fritzsche
If you're using C++, your structure is a class. So adding 'class-like' bits (constructors) isn't changing the PODness of it. Gunslinger's method will work even if you forget to initialise it, by declaring something myvar; for instance: that is a great benefit.
Brian Hooper
@Brian: Of course it does change the PODness - read a definition of POD types. They are restricted to a subset of the possibilities of normal class-types. If you don't need a POD use a constructor, but if you need C-compability, aggregate-initialization or say byte-wise serialization then you need alternatives.
Georg Fritzsche
Georg is correct
0A0D
I stand corrected.
Brian Hooper
A: 

Have you considered doing a memset(&struct, -1, sizeof struct) ? Or why not start at 0? Is there a reason you want -1? This is assuming, of course, all of your struct members are signed and not unsigned for the -1 to work.

You could also do this:

static const MyStruct structDefault = {-1, -1, etc};

void helper(const MyStruct& realStruct = structDefault) { }

If you want to modify the members of the realStruct, then you could mark it as mutable.

0A0D
`memset( in that case, `memset()` will set all int to 0xFEFEFEFE.The second proposition does not save the typing.
pascal
@pascal: But it does set it to the default value -1 though so I am still correct
0A0D
"by chance", just because 4 times `(unsigned char)-1` (0xFF) actually gives back 0xFFFFFFFF. This does not hold in general for any constant.
pascal
@pascal: Of course, but the OP's example had -1 so that's why memset works "by chance" in this case.
0A0D
+3  A: 

Make a union of your structure, and an array. And use a loop to initialize the array.

union something {
    struct {
       int a,b,c,d;
    };
    int init[4];
};

   something truc;
   for (int i=0; i<4; i++) truc.init[i] = -1;
pascal
hmm... this looks good, if i just could make the loop work with every struct that has init member? somehow get the size of init member into the for loop? is that possible?
Newbie
I get warning "nonstandard extension used : nameless struct/union" how can i avoid this error without disabling the error by using #pragma? and remain the functionality same?
Newbie
this is actually very elegant
Nathan Fellman
`for (int i=0; i<= i++) truc.init[i] = -1;` with `int init[];`
pascal