Skip to content

Intro To Variables and Operators

Glenn Salaman edited this page Sep 7, 2020 · 4 revisions

From Wikipedia:
"Variable (computer science): a symbolic name associated with a value and whose associated value may be changed"

To use variables in C, we must first declare them, like so:

int foo;

This declaration has a type and a name...in this case, int is the type (integer) and foo is the name.

  • Int is one of the built in C-types, which refers to a standard mathematical integer (positive and negative whole numbers...no fractions. Oh, and zero.)
  • You, as the programmer, get to choose the name...it can be almost anything, except for one of the keywords (you can't call it int for example). Naming things in software engineering can be tricky...try and pick good names. foo is probably not a good name.

This declaration can optionally have an initialization, like so:

int points = 100;

Operators

Now that we have our variable, what can we do with it? The first thing is "assignment", using the equals sign:

points = 50;

Note that the left side of the expression is our variable name (which needs to be previously declared), and the right side is a constant. We can also assign variables to other variables:

int start_points = 50;
int glenn_points = 0;

glenn_points = start_points;

If we look at the life of "glenn_points", it's initialized to 0, but then set to 50 at the assignment statement.

Next, we have math operators:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division

We can use these on both constants and variables, or any combination...and we can string them together. Here are some examples:

int start_points = 50;
int glenn_points;
int jeff_points;
int chris_points;
int total_points;
int average_points;

glenn_points = start_points + 200;
jeff_points = start_points + 100;
chris_points = start_points + 50;
total_points = glenn_points + jeff_points + chris_points;

Addition, subtraction and mulitplication are pretty straight forward, but division can be a little tricky: for integers, it truncates the result:

int division_example = 5/3;

This will return 1 (the truncated value) rather than 2 (the rounded value)

To get that remainder, c has a "modulus" operator: %

int mod_example = 3%2;

This returns the remainder...1 in this case.

increment and decrement

A very common operation is to add one or subtract one from a given variable. You can do so like this:

  my_number = my_number + 1;
  your_number = your_number - 1;

C gives a short-hand for doing this...the ++ and -- operators. Those look like this:

  my_number++;
  your_number--;

Advanced note: the ++ and -- can go either before or after the variable name (which has a slightly different order-of-operations effect), but for now, let's always put 'em after the variable.