Abort, Retry, Fail

Share this post

Intro to C, Part 6

www.abortretry.fail

Intro to C, Part 6

ternary and methods

Bradford Morgan White
Jul 29, 2012
Share this post

Intro to C, Part 6

www.abortretry.fail

Now for the ternary.

a = (x > 3 ? 2 : 10);

The above means: "if x is greater than 3 then a is equal to 2, otherwise a is equal to 10. Written in a form with which you are already familiar, the above is exactly equivalent to the following:

if (x > 3) {
  a = 2;
}
else {
  a = 10;
}

This can simplify some programs quite a bit, while in others it may not ever be needed.

#include <stdio.h>
int main( void ) {
  int c = 100, f = conv( c );
  printf("%d degrees centigrade is %d degrees farenheit.\n", c, f);
  return 0;
} // end main
int conv( c ) {
  int f = 32 + (c * 9)/5; return f;
} // end conv

So, I have introduced a few new things here. Let's look at main first. In main, I declare two variables, and I set them in two different ways. I give c a regular value, but I assign f the return value of the function "conv" which is being passed the variable c. In order to pass a variable from one function to another you need to have a variable listed in the function declaration, as can be seen in "int conv( c )". Another interesting thing to note is that f is assigned using an equation and is then used as the function's return value.

Intro To C, Part 6 By Bradford Morgan White
370KB ∙ PDF File
Download
Download

Share this post

Intro to C, Part 6

www.abortretry.fail
Comments
TopNewCommunity

No posts

Ready for more?

© 2023 Abort Retry Fail LLC
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing