-4
int a, b, i=10, j=20; 
a = (i,j); 
b = i,j ;` 

When I compile the above program in linux (g++) I am getting warnings at line number 2:

left-hand operand of comma has no effect)

and line number 3

(right-hand operand of comma has no effect).

I do not understand what is wrong.

3
  • What value would you expect a to have? i or j? Or both? ;)
    – BitTickler
    Apr 21, 2015 at 5:18
  • I want to print both Apr 21, 2015 at 5:24
  • @user2787274 "I want to print both " - well, std::cout << i << ' ' << j << '\n';, or if you want to save both in one variable and print them later, your could use a std::pair: #include <utility> std::pair<int,int> a { i, j }; std::cout << a.first << " ' << a.second << '\n';. Apr 21, 2015 at 6:10

1 Answer 1

1

What do you think this bit does?

 a = (i,j);

It's equivalent to:

a = j;

The compiler's just saying there's no point using the comma operator when the earlier terms have no side effects (i.e. evaluating i didn't "do" anything); given you've done something pointless, it assumes you did it by accident and is warning you to check....

That contrasts with something like this...

a = (++i, j);

...where there is a side effect of the evaluation of the first term: i is incremented.

1
  • b = i because comma has the least precedence of all operators - use parenthesis
    – Otomo
    Apr 21, 2015 at 5:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.