rulururu

post Comma Operator

June 17th, 2008

Filed under: C++ — Kai @ 10:23 am

A colleague of mine reported an error in the program flow. The line that was wrong looked like this (variable and class names are modified):

if(pCurrent->m_Array[r]->Match(((CMyClass*)this)->m_ptrAttr[i])), (CMyClass*)this)

We soon noticed that the number of braces in that statement is wrong. The ) before the comma closes the statement wrongly. Just a mistake you make when writing statement without paying attention.

Fix simply looked like this:

if(pCurrent->m_Array[r]->Match(((CMyClass*)this)->m_ptrAttr[i]), (CMyClass*)this)

The strange thing about it is that the compiler didn’t even throw a warning that we used a comma in that if statement. The comma operator seemed to be valid usage in C++ if statements.

I quickly looked it up and found out that the binary comma operator is almost only ever used for its side effects, as all it does is to ignore the value on its left and return the value on its right so.

that means

if( 0 , 1 )

always returns true because just the right side is considered.

I at first thought “Huh - that’s useless, what nonsense!” - but then I kept on reading what’s its second usage:

Its common usages is to sneak extra initialisation into a for’s loop init-expr e.g.:-

for ( i=0, j=0; ...

init-expr is an example of an expression whose value is not used, its only the side effect (initialisation) that matters.

Although this is definitely worse coding style you can use commas for the side effect if you want to. ;)

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)