In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
1) Is the following statement valid? If not, why not? If so, what does it do? int x = (1,024);
Functionally equivalent to: int x = 024;
What about the following?
y = 1,024;
Functionally equivalent to: y = 1;
2) How does cin >> ch differ from cin.get(ch) and ch = cin.get() in how it views input?
With formatted input (cin >> ch) all whitespace is skipped. With the form cin.get(ch) you have unformatted input extraction and ch may actually be a whitespace character. The form ch = cin.get() returns an int rather than a char which allows the return value to also become eof.
1) Is there any way to remember this, since with the parenthesis it accepts the 3 digits after the comma; but without the parenthesis it accepts the digit before the comma.
2) cin >> ch -- accepts a single character (alphabet or symbol) and doesn't accept white spaces
cin.get(ch) -- accepts anything (alphabet, symbols and whitespaces), and
ch = cin.get() -- accepts anything and stores it as an int.
I didn't quite follow the first example.
I understand that the comma has least precedence and ( ) has the highest precedence.
So, in the first example, (1,024) is evaluated first since it is in the brackets. Then the contents within the brackets are exactly the same as the second example, right? So, shouldn't x = 1; just like y in the second example?
Then the contents within the brackets are exactly the same as the second example, right?
Yes, the subexpressions are the same, but () doesn't evaluate to the internal subexpression (think about it. If it did, it would have no effect. For example, 2*(1+3) would equal 2*1+3). It evaluates to the value of the internal subexpression. The value of "1,024" is "024". Therefore, these two lines are equivalent:
According to the way the comma operator works the first operand (1) is evaluated and discarded. Next, the second operand (024) is evaluated and is used for the value of the expression. Now, that doesn't really matter here since the result of the expression is not used. But, if you stick the expression in a set of parentheses, that is the result you will get, and that is why x = (1, 024); results in x equaling 024.
Whereas in y=1, 024; the compiler sees it as the parenthetical expression (y=1), 024 where (y=1) is the first operand of the comma operator (see the precedence rules mentioned by giblit above.) So, y=1 is evaluated and the resulting value is discarded. The expression then takes on the value of second operand. However, that value is never used for anything.