Absurd: An Introduction to C

Part II, 20120616

Last time, we got into the absolute basics. This time, let's cover something more useful.

A variable is like a letter in algebra. You can make it something other than what it appears to be, and this can be quite useful. Unlike algebra, a variable can be ANYTHING. In C, you have to specify what type of something it is and what value the something is. So, you can declare "int foo" which means an integer (a whole, real number) whose name is foo. Let's see this in action.

#include <stdio.h>
int main(void) {
  int foo;
  int bar;
  foo = 0;
  bar = 2;
  printf("The value of foo is %d\n", foo);
  printf("The value of bar is %d\n", bar);
  foo = foo + 2; bar = foo + 8;
  printf("The value of foo is %d\n", foo);
  printf("The value of bar is %d\n", bar);

So, as you can see, we declare the variables as integers, and then we give them values. You could just as easily have done "int foo = 0, bar = 2;" and this would have made the first four lines in main a single line. This is a matter of preference. I would choose brevity, others might choose readability and verbosity. The next line that is interesting is "foo = foo + 2" which takes the present value of foo adds 2 to it and then reassigns the resulting value to foo. We could also write this "foo += 2". If you want to get more experience play with adding the variables together and adding more values in general. Other operators are "*" for multiplication, "-" for subtraction, "/" for division, "++" for increment, "--" for decrement, and "%" for modulo (remainder) -- quick note that % is also used in formatting and there does not mean modulo.

The printf statement has something a little different in it this time as well. You notice that %d? That means decimal value. So, we are printing the decimal value listed after the quotes. We could have combined the statements a bit by using 'printf("The value of foo is %d, and bar is %d", foo, bar);' The important thing to keep in mind is that the order of the variables will change when they are printed in the text.

⇠ back

© MMIX - MMXX, absurd.wtf
Licentiam Absurdum