简体   繁体   中英

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.

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.

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("\\na = %d", a),int(3); is evaluated like this:

  • printf("\\na = %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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM