0

I am writing some Win32 program. and I meet a problem. I define an array of Point,just like this:

   POINT points[3];

and now I want to Initialize it, and I know this is illegal

   POINT points[3] = { (295,295),(200,200),(400,500) };

so I need the correct way.

3
  • 3
    try POINT points[3] = { {295,295},{200,200},{400,500} }; Commented Dec 18, 2013 at 21:47
  • 2
    You don't really need the 3. Just let the computer do the counting for you. Commented Dec 18, 2013 at 21:48
  • @user3116182: Illegal? It doesn't do what you apparently want it to do, but it is certainly not illegal. The code will compile. Commented Dec 19, 2013 at 0:30

2 Answers 2

2

You can do it simply as

POINT points[3] = { 295, 295, 200, 200, 400, 500 };

but a safer thing to do would be this

POINT points[3] = { { 295, 295 }, { 200, 200 }, { 400, 500 } };

The amusing part is that what you originally wrote is not illegal (where did you get that idea?). The () you used inside your initializer will cause the inner , to be interpreted as comma operator. For example, expression (400, 500) evaluates to 500. That means that your original initializer is actually treated as

POINT points[3] = { 295, 200, 500 };

which is in turn equivalent to

POINT points[3] = { { 295, 200 }, { 500, 0 }, { 0, 0 } };

It doesn't do what you want it to do, but it is certainly not illegal.

Sign up to request clarification or add additional context in comments.

3 Comments

nice answer. I am sorry that my expression is not rigorous.
Can you tell me more about inner comma operator, such as its source code. @AndreyT
@user3116182: Comma operator in your original code case is a built-in operator, part of core C++ language. It has no "source code". There's plenty of info about it on the Net (en.wikipedia.org/wiki/Comma_operator).
0

As per the comments:

POINT points[] = {{295,295}, {200,200}, {400,500}};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.