'Do invalid statements provide valid results [duplicate]
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silvio Mayolo |
