-2
#include <stdio.h>

int main()
{
    int x = 1;

    if (++x > 2,5)
        printf("%d", ++x);
    else
        printf("%d", x++);
}

I don't understand why the output is 3. ++x == 2 and 2 > 2,5 is false. But the compiler says the if statement evaluates to true. What is the reason?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
bekici
  • 68
  • 10
  • 1
    Because `5` is `true`, which is evaluated after `++x > 2` – Weather Vane Jan 01 '20 at 19:13
  • 3
    `2,5` is not what you think it is. – machine_1 Jan 01 '20 at 19:13
  • 3
    Use dot `.` for the decimal point in C source code. Use comma `,` to separate arguments to functions, or as the comma operator but beware — the comma operator causes confusion very easily. You're using it as a comma operator, whether you know it or not. (And a consequence of using a comma operator is that `2 > 2,5` evaluates as if you'd written `++x; if (5) …` and `5` is true, not false as you said in the question.) – Jonathan Leffler Jan 01 '20 at 19:15
  • 1
    @P__J__ — I didn't immediately find a question that covers the correct syntax for a `double` constant. The best I can suggest is the C standard itself: C11 [§6.4.4.2 Floating constants](http://port70.net/~nsz/c/c11/n1570.html#6.4.4.2). There is no provision there for the use of comma as the decimal point. I/O can use locales ([`setlocale()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setlocale.html) and [`localeconv()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/localeconv.html)) to use comma as the decimal point. – Jonathan Leffler Jan 01 '20 at 19:27
  • 1
    @P__J__ I used that duplicate because it seems to answer the *actual* question: "What is the reason [the `if` statement evaluates to `true`]?" – Weather Vane Jan 01 '20 at 19:30
  • 1
    @thinkblue Should be `2.5`. The creators of C weren't thinking about other countries, huh? – S.S. Anne Jan 01 '20 at 19:35
  • I'm not sure why the entire conversation is about `,` and `.` . I'm sure that @thinkblue has not made a mistake here by using 2,5 instead of 2.5. His question is why as per below code if statement evaluates to true `if ( 2 > 2,5 ) printf("Yes 2 is greater"); else printf("No 2 is not greater");` – Deepak Yadav Jan 02 '20 at 12:33

1 Answers1

0

2,5 is not the correct syntax for a double constant. 2.5 is. Which is probably unfortunate for people living in countries where , is the decimal point.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
  • I'm sure that @thinkblue has not made a mistake here by using 2,5 instead of 2.5. His question is why as per below code if statement evaluates to true `if ( 2 > 2,5 ) printf("Yes 2 is greater"); else printf("No 2 is not greater");` – Deepak Yadav Jan 02 '20 at 12:30