-2

I made this code and it should be invalid

#include<iostream>
using namespace std;

int main()
{
  int a,b;
  a=3,014;    //invalid
  b=(3,014);  //invalid
  cout<<a<<endl<<b;
}

Output:

3
12

However both the invalid statements give valid results. But the result should be 3014. It is changed. Why does this happen?

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
JRBros
  • 43
  • 6
  • You might also be interested in reading [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/11082165) – Brian61354270 Apr 22 '22 at 01:56
  • You might be interested to know that since C++14, you can use single quotes as [digit separators](https://en.cppreference.com/w/cpp/language/integer_literal). So e.g. `a = 3'014;` would assign `3014` to `a`, but you'd have the readability improvement from a separator. – Nathan Pierson Apr 22 '22 at 02:01
  • The first 'invalid statement' isn't invalid. The second one doesn't compile as shown, because of the period, so it can't produce anything. If the period is a typo and shouldn't be there, that statement isn't invalid either. – user207421 Apr 22 '22 at 02:20

1 Answers1

4

There's nothing "invalid" about either of those.

a = 3,014;

This parenthesizes as

(a = 3) , 014;

So a gets assigned the value 3, and then 014 (a number) gets evaluated and discarded. Hence, a = 3.

b = (3 , 014);

Here, we've explicitly put in parentheses. So the right-hand side is an application of the comma operator. The 3 gets evaluated then discarded. The 014 is an octal number, and 14 in base 8 is equal to 12 in base 10, so b = 12.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116