3

I come from a country where the way we write decimal numbers differs from the other place by whether I use ',' or '.' for decimal separator. Now this is why I by accident wrote somewhere in my c++ program:

while(true){
    long double x=0;
    //some code that increases the value of x 
    //by very small amount but it doesn't leave it at 0
    if(x>0,000001)break;
}

And this made the program run indefinitely. After wasting quite some time thinking my code was wrong I tried this:

while(true){
    long double x=0;
    //some code that increases the value of x 
    //by very small amount but it doesn't leave it at 0
    if(x>0.000001)break;
}

Which worked just fine. Later I understood my mistake (I used ',' instead of '.'), but now I am confused as to why doesn't the next code result with compilation error, and how come it's outcome is "greater"

long double g=0.001;
if(g>0,01)cout<<"greater";
else cout<<"smaller";

Edit: When I posted this question I didn't know that the comma is an operator. So the question was marked as duplicate and lead here How does the Comma Operator work . But there I couldn't actually find a comparison between '.' and ',' .

  • 7
    Look up "comma operator" – milleniumbug May 01 '18 at 18:46
  • Related: [How does the comma operator work?](https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work). – WhozCraig May 01 '18 at 18:48
  • Oh, I didn't know that. Thank you, but that is still harder to catch here. Using straight up values rather than variables. – Martin Dinev May 01 '18 at 18:48
  • 1
    You should enable your compiler's warnings. – Quentin May 01 '18 at 18:56
  • actually , I think in all countries "digital" standard became to use period for fraction separator instead of comma for this exact reason. I'm from such country,Russia, myself and it started to change. – Swift - Friday Pie May 01 '18 at 19:14
  • @Quentin not all compiler warn about this. Not all even warn about ; after if(). Also, not all people read warnings, but that's different issue :P – Swift - Friday Pie May 01 '18 at 19:15
  • @MartinDinev: "*But there I couldn't actually find a comparison between '.' and ',' .*" You don't need one. You simply need to know that the comma doesn't mean what you think it means. Comparing the two is like comparing `if` with `+`; they're fundamentally different on every level. – Nicol Bolas May 01 '18 at 19:26

1 Answers1

3

, in C++ is an operator which returns the value of its second operand. So a, b evaluates to b.

, also has very low precedence, so your comparisons are actually evaluated as:

if((x>0), 01) -> if(01) -> if(true)

Gordon Bailey
  • 3,881
  • 20
  • 28
  • comma allows to exploit for() because of this. Also allows to create fancy asserts or use ternary operator in quite strange way. Not that I would appreciate to see that in code that wasn't made into a well-documented template or macro. – Swift - Friday Pie May 01 '18 at 19:19