tags:

views:

80

answers:

2

I have a struct that I initialize like this:

typedef struct
{
 word w;
 long v;
}
MyStruct;


MyStruct sx = {0,0};
Update(sx);

Now, it seems such a waste to first declare it and then to pass it. I know that in C#, there's a way to do everything in one line. Is there any possiblity of passing it in a more clever (read: cleaner) way to my update function?

+7  A: 

In C++, structs are the same as classes except in structs everything is public by default. So you can give a struct a constructor, e.g.

struct MyStruct
{
 word w;
 long v;

 MyStruct(word w, long v) : w(w), v(v) {}
};


Update(MyStruct(0,0));

Also, C-style struct typedef'ing is unnecessary and discouraged in C++.

Tyler McHenry
+1 on using the constructor. The typedef in C++ actually makes a slight difference (from just naming the struct with the name) but in most cases it will be unnoticed and unimportant (and it is most probably not the reason why it was in the question's code)
David Rodríguez - dribeas
+5  A: 

It depends on how your Update is declared. If it expects a value of MyStruct type or a reference of const MyStruct& type, you can just do

Update(MyStruct());

This is possible because you wanted to initialize your object with zeroes (which is what the () initializer will do in this case). If you needed different (non-zero) initializer values, you have to either provide a constructor for MyStruct or do it the way you do it in your question (at least in the current version of the C++ language).

AndreyT