Fun with comma


Some time back I have encountered a weird coding error. Can you make out any problem in code given below?



#include <iostream>
void Function(int argument1, int argumentWithDefaultValue = 10)
{
    std::cout << argument1 << std::endl;
    std::cout << argumentWithDefaultValue << std::endl;
}

int main()
{
    Function((1111, 2222));
    return 0;
}


 Any guess, what values would it print on the console. If your guess is



1111
2222

 then you are wrong. Actually this code prints



2222
10

Wondering, what is going on here? In order to understand this, you first need to understand the difference between comma separator and comma operator. The commas used between function arguments are the punctuations to separate the arguments; this usage is sometimes referred as comma separator. Whereas, the purpose of comma operator is to allow grouping of two statements where one is expected. The comma operator does the left to right evaluation of the operands. For example in following code comma in z = x, y is comma separator used



int x = 1111, y = 2222;
int z;
z = x, y;      // comma separator: z = 1111
std::cout << z << std::endl;
z = (x, y);    // comma operator: evaluated left to right
               // z = 2222
std::cout << z << std::endl;

for separating the x and y. Whereas comma in z = (x, y) is a comma operator that evaluates the expression x, y in left to right sequence and returns the value of y.
Now after understanding this difference, you can easily make out that due to extra pair of parentheses, expression (1111, 2222) is evaluated in left to right sequence (comma is treated as comma operator) manner. So the resulting value 2222 is passed to first argument of the Function and the default value 10 is passes to second argument. Funny!
Additionally, note that the code will not compile for obvious reasons if you remove the default value of the second argument.
Fun with comma Fun with comma Reviewed by Sourabh Soni on Sunday, March 14, 2010 Rating: 5

No comments

Author Details

Image Link [https://3.bp.blogspot.com/-zo21XIdyPqc/VuTrFfUyPhI/AAAAAAAAAO8/EEWTN73XHUA7aTIjuxuBSN-WGaGkNUymA/s1600/sourabhdots3.jpg] Author Name [Sourabh Soni] Author Description [Technocrat, Problem Solver, Corporate Entrepreneur, Adventure Enthusiast] Facebook Username [sourabh.soni.587] Twitter Username [sourabhs271] GPlus Username [#] Pinterest Username [#] Instagram Username [#] LinkedIn Username [sonisourabh] Youtube Username [sonisourabh] NatGeo Username [271730]