2.7. Declaring Variables

A variable is an allocated data storage container. The name given to a variable is determined by the programmer, thus the name is referred to as an identifier.

There are a few limitations on the allowable name for variables.

  • Identifiers may contain any alphanumeric characters (a-z, A-Z, 0-9) as well as underscores (_).
  • Must not contain spaces. Consider camel or underscore style for multi-word names.
  • Must not contains special characters other than the underscore.
  • Must not begin with a number.
  • Must not be one of the keywords of the language.

(See Identifiers )

2.7.1. Basic data types

float x;
int y;
char ch;

int a, b, c;

int count = 100;
char s = 'S';

The following modifiers may also used when declaring integer data types: signed (default), and unsigned.

Name Use Size
int Interger (whole) numbers 32 bits
short Interger (whole) numbers 16 bits
long Interger (whole) numbers 64 bits
char ASCII letters 8 bits
float real numbers with a decimal point 32 bits
double real numbers with a decimal point 64 bits

2.7.2. Constants

We already saw the #include pre-processor directive. The other pre-processor directive is #define, which can be used to define constants.

#define LIMIT 100
#define PI 3.141593
#define G0 "Let's get going"

These constants are called symbolic constants. When constants are used in the body of the code, the pre-processor replaces the constant with its value before the compiler sees it, so it is as if the value was hard coded into the code. The advantage of using constants is that they make the meaning more clear and by changing the value of the constant, one can change several lines of code at once.

2.8. Arithmetic operations and assignments

Simple assignment is of the form: variable = value;

Basic arithmetic assignments are: + - / * %

Only lesser known of these is the modulus operator, which means remainder after integer division. So, 17 % 3 = 2

In a C program, assignment based on arithmetic operations looks like:

x = y + z;
i = j * k;
p = (int)(x / z);
t = u % v;

C also has some special assignment operators:

i++;  // Is the same as i = i + 1;
i--;  // Is the same as i = i - 1;

i+=5;    i*=5;    i/=5;     // are the same as:
i = i+5; i = i*5; i = i/5;

j = (x < y) ? k : l; // we will talk about this one later

The last of these means that j takes the value of k if x < y. If the evaluated expression is not true (x >= y), then j takes the value of l. (see Conditional Operator)