# c++ magic or ?

This topic is 3785 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How can this work?

struct Vec
{
float x, y, z;

Vec(float a, float b, float c)
{
x = a;
y = b;
z = c;
}

void operator *= (float a)
{
x = a;
y = a;
z = a;
}
};

int main()
{
Vec a(0, 0, 0);

a *= (1.3f, 0.5f, 0.8f, 0.4f);

cout << a.x << ", " << a.y << ", " << a.z;
}


This seems to be legal, and the result is:
0.4, 0.4, 0.4



##### Share on other sites
Because of the comma operator.
This:
a *= (1.3f, 0.5f, 0.8f, 0.4f);
Means:
1.3f; 0.5f; 0.8f; a *= 0.4f;
(More or less)

##### Share on other sites
Comma operator. It performs consecutive assignments. Put a std::cout into your *= operator to see what happens.

Not the best idea though.

##### Share on other sites
Ahhh, I see. Interesting, so comma is actually a operator. I didn't know that. Thanks! :)

##### Share on other sites
??? So why is 0 * 0.4 equal to 0.4 here?

-Scott

##### Share on other sites
its not 0 * 0,4 as in mathematical zero "times" 0,4

it's * operator that defines * as =

void operator *= (float a)
{
x = a;
y = a;
z = a;
}

so what this really do is just setting x,y,z to a,a,a

##### Share on other sites
Quote:
 Original post by popsoftheyear??? So why is 0 * 0.4 equal to 0.4 here?-Scott

Because his custom *= operator doesn't perform multiplication, just assignment.

##### Share on other sites
*Kicks self*
Thanks - I'm gonna go get some coffee

-Scott

##### Share on other sites
#include < iostream >#include <vector>#include <map>#include <boost/assign/std/vector.hpp>#include <boost/assert.hpp>using namespace std;using namespace boost::assign;int main() {  vector<int> v;   v += 1,2,3,4,5,6,7,8,9;  map<string,int> m;   insert( m )    ( "Bar", 1 )    ( "Foo", 2 )    ;  std::cout << "This shit is crazy\t" << v[4] << "\t" << m["Bar"] << "\n";}

Now that's some crazy code. Yes, "," is an operator. So is "()()"

1. 1
2. 2
frob
15
3. 3
Rutin
11
4. 4
5. 5

• 13
• 14
• 62
• 14
• 15
• ### Forum Statistics

• Total Topics
632128
• Total Posts
3004270

×