Comma Operator - Examples

Examples

In this example, the differing behavior between the second and third lines is due to the comma operator having lower precedence than assignment.

// Examples: Descriptions: Values after line is evaluated: int a=1, b=2, c=3, i=0; // comma acts as separator in this line, not as an operator ... a=1, b=2, c=3, i=0 i = (a, b); // stores b into i ... a=1, b=2, c=3, i=2 i = a, b; // stores a into i. Equivalent to (i = a), b; ... a=1, b=2, c=3, i=1 i = (a += 2, a + b); // increases a by 2, then stores a+b = 3+2 into i ... a=3, b=2, c=3, i=5 i = a += 2, a + b; // increases a by 2, then stores a into i. Equivalent to (i = (a += 2)), a + b; ... a=5, b=2, c=3, i=5 i = a, b, c; // stores a into i ... a=5, b=2, c=3, i=5 i = (a, b, c); // stores c into i ... a=5, b=2, c=3, i=3

Note that comma cannot be used in indexing multidimensional array: the code A evaluates to A with the i discarded, instead of the correct A. This differs from the syntax in Pascal, where A is correct, and can be a source of errors.

Read more about this topic:  Comma Operator

Famous quotes containing the word examples:

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)