A comma in an if or while

Apr 23, 2010 at 8:54pm
That title is odd i know but I just couldn't think of a short and easy way to sum it up. Basically, I remember reading on one of the forum threads that if you had for example: if(/*statement 1*/, /*statement 2*/); that statement 1 would always be true and would always be executed. Firstly, is this true? And if so, what are peoples views on using this?

This is an example of code that I have use this method with:

1
2
if(getline(std::cin, strInput), !(strInput.compare("")))
	continue;
Apr 23, 2010 at 9:03pm
This reminds me of this: http://www.cplusplus.com/forum/beginner/22678/

If I remember correctly, the sub-statements will all be executed but only the last one (on the right) will be used for the condition.

As far as my view on when its use is appropriate, I vote for never.
Last edited on Apr 23, 2010 at 9:05pm
Apr 23, 2010 at 9:08pm
I vote for never, and I hope that when C++0x comes out, it's not just deprecated, it's removed.

Okay, it has its uses.

-Albatross
Last edited on Apr 23, 2010 at 9:22pm
Apr 23, 2010 at 9:15pm
It's the purpose of the comma operator, it executes the left operand and returns the right one
It's quite a good feature. The problem is that some people read it as 'and' or something like that
It shouldn't be removed or deprecated

http://www.cplusplus.com/doc/tutorial/operators/
Last edited on Apr 23, 2010 at 9:16pm
Apr 23, 2010 at 9:27pm
All right, the operator has its uses in the contexts listed.

I still vote for never. In my opinion, we should limit the number of calculations we do per inter-semicolon space. However, that comma in that context is basically just a way of fitting as many of those calculations as possible into a certain line. And when you have an if attached to that...

-Albatross
Apr 25, 2010 at 7:06pm
Thanks for your replies people!
Apr 25, 2010 at 8:15pm
I'm with Albatross. Although it has it's uses, it looks very abusable. Still it shouldn't be deprecated or removed.
Apr 26, 2010 at 10:02pm
@chrisname ... With regards to my example, what are you're thoughts?
Apr 26, 2010 at 11:34pm
If the standards committee took away a C++ feature that at least one member of the forum was uncomfortable with /or afraid to use, there would be fu*kall left of the language.
Apr 27, 2010 at 1:15am
Removing that operator would break this for (/*...*/;a++,b--) //... and this #define M(x) (x+=1, x*2) .
It's very easy to update a language when you don't have to deal with minutia, such as backwards compatibility. The problem is that you do have to, and removing operators is one of those things that break it.

Hey, since we're removing operators, why not merge assignment and equality into a single operator and add <> as inequality? Surely nothing can go wrong there!
Topic archived. No new replies allowed.