October 22, 2024
Chicago 12, Melborne City, USA
C#

Convention for C ternary conditional operator


Considering the ternary operator ?: in C, I have found 3 common conventions used with it (specifically for variables, as the convention there with the other areas of formatting I assume applies to non-variable assignment uses of the operator).

Which one of the valid syntaxes below is standard (the most common/proper convention), and is it mentioned in any documentation?

int i;

Different expressions (bool is being used to represent some Boolean expression):

i = bool ? 1 : 0

i = (bool) ? 1 : 0

(bool) ? i = 1 : i = 0 (convention assumes the preferred of the above two)

K&R mentions in chapter 2.11, Conditional Expressions, to advise the second of the two first options, to more easily read the Boolean expression from the rest of the conditional.
K&R, however, does not make any recommendations as to whether, when using the operator with assignments, to prefer the third option, or one of the two previous ones.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video