A comma instead of a semicolon. Why doesn't this statement give a 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 line printfdoes not work in C. Why does it work in C++? I got confused that the comma is allowed between the two statements and the C / C ++ compilation difference.

+3
source share
2 answers

int(3) Invalid syntax in C. You could write it like this:

printf("\n a = %d", a),(int)3;

or even just:

printf("\n a = %d", a),3;

and this will be compiled in both C and C ++.

Note that the comma between printfand the redundant expression following it is only a comma . The results of both the printf call and the next expression are discarded.

+11

, int(3) ++, , . C, .

Paul R, ++, , (comma operator) , ( ).

, ++ printf("\n a = %d", a),int(3); :

  • printf("\n a = %d", a). .
  • 3 int, , .
+2

All Articles