8/7 Is there a way to assign values to a structure in one statement? e.g.
my_struct_t m1, m2;
m2 = m1; /* compiles*/
m2 = {1,2,3}; /* doesn't compile */
Thanks.
\_ give my_struct_t a constructor. pass 1,2,3 as arguments.
m2 = my_struct_t(1,2,3); --pld
\_ if he's using C++, another way to do it is to define
operator<< and/or operator,
then you can do intuitive looking things like:
Array ar;
ar << 1,3,4,5,6;
i don't remember the precedence of operator= but if it's
lower than that of operator,
you could also do
ar = 1,2,3,4,5;
\_ oh shit, you're asking for hell from the language lawyers.
you can't do that at runtime but you can use that syntax as an
initializer. that's why it's called "initializer" syntax.
\_ Yes, you can say my_struct_t m2 = {1, 2, 3};
\_ I need to assign different values multiple times, hence I can't
do it as initialization. Oh well, I'll just have to do it field
by field then.
\_ yeah, quit being such a lazy ass and do it by field.
\_ have you read up on these things called "classes" by the way?
\_ Been out of school for too long. I can't even find my K&R
book anymore.
\_ I have a copy, but it's in Russian :(. As for your
question -- yeah, you can't use struct initialization
as assignment in C. If you need it a lot, you can write
a macro. -- misha.
\_ this isn't terribly efficient, but can't you declare and
initialize a temporary structure, and then assign that to the
one you really want? e.g.:
{ my_struct temp = { x, y, z };
whatever = temp;
}
...? yeah, it's not a single line answer, but it's simple.
and if you're lucky, maybe your compiler will do the right
thing and ditch that temporary structure entirely. -jameslin
\_ i think c99 allows this. you are using c99, right? -ali |