Reputation: 3479
#include <iostream>
using namespace std;
int main() {
// your code goes here
int a = 10;
printf("\n a = %d", a),int(3);
return 0;
}
This code works fine in C++ (http://ideone.com/RSWrxf) but the same printf
line does not work in C. Why does it work in C++
? I'm confused about comma being allowed between two statements and C/C++ compilation difference.
Upvotes: 3
Views: 519
Reputation: 92335
The reason why int(3)
works in C++ is because it's a functional cast. This isn't supported in C, which is why it fails there.
As Paul R already explained, the statement works in C++ since the ,
(comma operator) simply ignores the return value of the expression to the left of the ,
(but does execute it).
So in C++, the line printf("\n a = %d", a),int(3);
is evaluated like this:
printf("\n a = %d", a)
is executed. It's result is discarded.int
, but since it isn't assigned to a variable this statement has no effect and is discarded.Upvotes: 2
Reputation: 212969
int(3)
is not valid syntax in C. You could write it like this though:
printf("\n a = %d", a),(int)3;
or even just:
printf("\n a = %d", a),3;
and this would compile in both C and C++.
Note that the comma between the printf
and the redundant expression following it is just the comma operator. The results of both the printf call and the following expression are discarded.
Upvotes: 11