Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

syntax

#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.

like image 784
user13107 Avatar asked Jan 23 '26 22:01

user13107


1 Answers

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.

like image 100
Paul R Avatar answered Jan 25 '26 11:01

Paul R