View Single Post
  #6   Spotlight this post!  
Unread 03-05-2005, 09:37
Chris Hibner's Avatar Unsung FIRST Hero
Chris Hibner Chris Hibner is offline
Eschewing Obfuscation Since 1990
AKA: Lars Kamen's Roadie
FRC #0051 (Wings of Fire)
Team Role: Engineer
 
Join Date: May 2001
Rookie Year: 1997
Location: Canton, MI
Posts: 1,488
Chris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond reputeChris Hibner has a reputation beyond repute
Re: Functions of '?', ':', and '&' in the C programming language

Quote:
Originally Posted by GW (Greg) Ross
The ?: is called the ternary operator because it takes three operands. It's shorthand for "If the first operand is true, return the value of the second operand, otherwise, return the value of the third."

The & is a bitwise AND. The value returned has a 1 in each bit that is set in both operands. All other bits are zero.

In this example, the low order bit of Tx_Buffer is tested, and if it is set, TX_OUTPUT_PIN is assigned the value SERIAL_1, otherwise SERIAL_0.

BTW, I generally steer away from using the ternary operator. The following is much clearer:
Code:
if (Tx_Buffer & 0x01 == 1) 
  TX_OUTPUT_PIN = SERIAL_1;
else
  TX_OUTPUT_PIN = SERIAL_0;
As much as I hate "yeah, me too" posts, I'm going to do it here...

I strongly recommend staying away from the ternary operator. I also strongly recommend staying away from any other practice that makes your code less clear than it has to be. Good clear code trumps keystroke efficiency in all cases - don't forget that.

During the FRC Championship conference, myself and a colleagure presented an "Advanced C Programming" lecture. The main focus of the lecture was to show how C programming is done in the real-time embedded industry. We tried to impress as much as possible on "good coding practices". While it wasn't in the presentation, we made mention of staying away from the ternary operator (as well as recursion, compound statements, leaving out the {} from code blocks, etc.).

The following web page: http://www.andromeda.com/people/ddyer/topten.html is a great list of C "gotcha's". 90% of them are avoided by using the good practices we recommend. As a side note, the good coding practices that we recommend are basically part of a coding standard that is typical in industry.

Okay, sorry for getting this thread off topic...
__________________
-
An ounce of perception is worth a pound of obscure.