0

I was working with conditionals in c. While coding I found that this code is not working

int x = 1;
printf(1>0? "%d",x : "0");

Now, 1 is obviously greater than 0. So the program should print the value of x. But it actually never prints anything! I am using Codeblocks 17.12 and my compiler is MingW

  • Your output is a compiler error: https://ideone.com/kDz3Bi an error and a warning, to be correct. – mch Feb 13 '19 at 10:16
  • 1
    Enable compiler warnings: *warning C4047: ':': 'int' differs in levels of indirection from 'char [2]'*. – Weather Vane Feb 13 '19 at 10:16
  • If that even cleanly compiles it's because you're not enabling warnings and/or not treating them as errors. `"0"` and `x` are completely different types, therefore the second expression in your [comma operation](https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do) does not match the first for type compatibility. – WhozCraig Feb 13 '19 at 10:17

3 Answers3

3

It is working as specified. Unfortunately, you are misusing it. You seem to expect that the condition check should produce one of two function invocations:

printf("%d",x);
printf("0");

That's now not how C works. You use the conditional expression, so the result must be a single value, which translates to a single function argument. The comma you wrote is not the comma which is used to separate arguments to functions. It is the comma operator, which is an expression itself.

The semantics of the expression "%d", x is to evaluate "%d", discard the result, and then evaluate x. x is the result of the expression with the comma operator.

Which means your function call is equivalent to

printf(1 > 0 ? x : "0");

You pass an integer where a pointer to a string is expected. A decent compiler should flag that with a warning at least, and if yours doesn't you need to give it the proper flags to warn you about this.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
2

You have errors in your code.

Try this:

printf("%d", 1 > 0 ? x : 0);

I invite you to check the printf documentation and some ternary operator examples to better understand what is wrong with your code.

Leo
  • 741
  • 6
  • 14
0

Try this

printf(1 < 0 ? "0": "%d",x);
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103