Absurd: An Introduction to C, VI


Now for something odd.

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.

⇠ back

© MMIX - MMXXII, absurd.wtf

Licentiam Absurdum