Reputation: 55
I have on situation, where i need to keep the value float as well as int. so tried like below. but no help. can any one help on this?
union Val {
int a;
float b;
};
Val p;
p.b = 45.56;
int k = p.a; // i want k should be 45;
Upvotes: 0
Views: 1333
Reputation: 38919
I see that you say:
i dont want each time it to be converted from float to int [sic]
To do that you could use user-defined conversions to accomplish this.
So your struct would look like this:
class Val {
int a;
float b;
public:
Val& operator= (const int _a) {a = _a; b = _a + fmod(b, 1.0F); return *this;}
Val& operator= (const float _b) {b = _b; a = trunc(_b); return *this;}
operator int() {return a;}
operator float() {return b;}
};
Please note that what you really want to use is simply a float
with static_cast<int>
For astatic_cast
:
No checks are performed during runtime to guarantee that the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, it does not incur the overhead of the type-safety checks of
dynamic_cast
.
I've provided an example of using Val
here: http://ideone.com/XUesib but you could accomplish the exact same thing given float foo
like this:
foo = 1.3F;
cout << static_cast<int>(foo) << endl << foo << endl;
foo = 13 + fmod(foo, 1.0F);
cout << static_cast<int>(foo) << endl << foo << endl;
Upvotes: 1
Reputation: 238331
I have on situation, where i need to keep the value float as well as int. so tried like below
You can't do it with a union. A union can only hold a single value inside at any time. You need two separate variables. You can keep them in side a struct if you like:
struct Val {
int a;
float b;
};
Now you can have both an int and a float.
Val p;
p.b = 45.56;
p.a = p.b;
int k = p.a; // no conversion
That said, since you apparently only use a
to store a converted value of b
, you should measure whether the conversions even affect performance.
Upvotes: 1
Reputation: 329
You can use structure with constructor, and initialize your variables in it as you wish.
struct Val {
int a;
float b;
Val(float value) {
a = b = value;
}
};
So you can use it in loop and don't worry about conversations each time, just create your Val
variable outside loop and use it.
Upvotes: 0