By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,985 Members | 1,776 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,985 IT Pros & Developers. It's quick & easy.

confused about ? and : in a line of code for lcm

P: 1
I am researching ways to calculate lcm and came across this line and am trying to understand what it is saying, or possibly a more basic way to write it

lcm = (userNum1 > userNum2) ? userNum1 : userNum2;

The code runs fine, but if I don't understand it, I'm not going to be able to comprehend how to use it later.
Mar 26 '17 #1

✓ answered by weaknessforcats

The ?: is the ternary operator from C. It's the same thing as

Expand|Select|Wrap|Line Numbers
  1. if (userNum1 > userNum2)
  2. {
  3.     icm = userNum1;
  4. }
  5. else
  6. {
  7.     icm = userNum2;
  8. }
The theory is that the less code you write the less assembly code will be generated by the compiler. So a ?: will be the same as if/else but will produce less object code than if/else.

Now this was all true in 1968 with an 8-bit word on a machine with 32K memory.

With today's processors you can ignore any benefit obtained by ?:. I wouldn't use it myself.

Share this Question
Share on Google+
3 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
The ?: is the ternary operator from C. It's the same thing as

Expand|Select|Wrap|Line Numbers
  1. if (userNum1 > userNum2)
  2. {
  3.     icm = userNum1;
  4. }
  5. else
  6. {
  7.     icm = userNum2;
  8. }
The theory is that the less code you write the less assembly code will be generated by the compiler. So a ?: will be the same as if/else but will produce less object code than if/else.

Now this was all true in 1968 with an 8-bit word on a machine with 32K memory.

With today's processors you can ignore any benefit obtained by ?:. I wouldn't use it myself.
Mar 26 '17 #2

Expert 100+
P: 2,396
The ternary operator offers a potential marginal benefit when used like the OP code example; you only type the left-side variable name once so you don't have a chance to accidentally type different names in the two legs of the if-else.
Mar 27 '17 #3

Expert 100+
P: 2,396
The ternary operator is one of the goto-constructs in The Obfuscated C contest:
http://scrammed.blogspot.com/2012/04...-its-best.html
Mar 27 '17 #4

Post your reply

Sign in to post your reply or Sign up for a free account.