Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying increment to ternary operator in C

I thought that the ternary operator returns either a value on the left side or the right side of : depending on the condition. Why does this following piece of code print 1?

#include <stdio.h>

int main(int argc, char const *argv[]) {
  int c = 0;
  (c?c:0)++;
  printf("%i", c);
  return 0;
}
like image 998
shreyasva Avatar asked Dec 21 '22 11:12

shreyasva


1 Answers

You would appear to have a compiler bug, or perhaps a language extension, since this is not valid C. You need an lvalue in order to apply the ++ operator, and (c?c:0) is not an lvalue.

like image 130
David Heffernan Avatar answered Dec 24 '22 02:12

David Heffernan