Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this ternary conditional ?: correct (Objective) C syntax?

People also ask

What is the correct syntax of ternary operator in C?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");

What is the correct syntax for conditional or ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is ternary condition in C?

Programmers use the ternary operator for decision making in place of longer if and else conditional statements. The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.

Which is the conditional operators ternary operator used in C?

Overview. The conditional operator is the one and only ternary operator in the C programming language. It can be used as an alternative for if-else condition if the 'if else' has only one statement each.


From http://en.wikipedia.org/wiki/%3F%3A

A GNU extension to C allows omitting the second operand, and using implicitly the first operand as the second also:

a = x ? : y;

The expression is equivalent to

a = x ? x : y;

except that if x is an expression, it is evaluated only once. The difference is significant if evaluating the expression has side effects.


This behaviour is defined for both gcc and clang. If you're building macOS or iOS code, there's no reason not to use it.

I would not use it in portable code, though, without carefully considering it.


$ cat > foo.c
#include <stdio.h>

int main(int argc, char **argv)
{
  int b = 2;
  int c = 4;
  int a = b ?: c;
  printf("a: %d\n", a);
  return 0;
}
$ gcc -pedantic -Wall foo.c
foo.c: In function ‘main’:
foo.c:7: warning: ISO C forbids omitting the middle term of a ?: expression

So no, it's not allowed. What gcc emits in this case does this:

$ ./a.out 
a: 2

So the undefined behaviour is doing what you say in your question, even though you don't want to rely on that.


This is a GNU C extension. Check you compiler settings (look for C flavor). Not sure if it's part of Clang, the only information I could get is in this page:

Introduction

This document describes the language extensions provided by Clang. In addition to the language extensions listed here, Clang aims to support a broad range of GCC extensions. Please see the GCC manual for more information on these extensions.