user13107
user13107

Reputation: 3479

Comma instead of semicolon, Why does this statement not give syntax error in C++?

#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

Answers (2)

DarkDust
DarkDust

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.
  • The number 3 is cast to int, but since it isn't assigned to a variable this statement has no effect and is discarded.

Upvotes: 2

Paul R
Paul R

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

Related Questions