C Programming - Quick Reference Guide

C Keywords

autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
constfloatshortunsigned
continueforsignedvoid
defaultgotosizeofwhile
doifstatic 

Variables

Variables are of type int, char, double, or float. The modifiers auto, signed, unsigned, and extern may be applied to any of these. The modifiers long and short may be applied to int. When using long and short, int may be omitted. Variables are of type auto automatically, so the "auto" keyword is rarely used. Signed variables may contain negative numbers; unsigned variables may not.

A char is one byte wide. A short is two bytes wide. A long is four bytes wide. The width of an int depends on the computer. DOS has a 16-bit (2 byte) int; Windows and most Unix systems have a 32-bit (4 byte) int. 64-bit (8-byte) ints also exist. Floats and doubles allow the use of decimal points. A float is typically four bytes, a double eight bytes. The more bytes in a variable type, the larger a value it can hold.

Variable names may use any letter or number, or the underscore. A name may not, however, begin with a number. Variable names have a long limit, depending on the compiler (typically about 30 or 60 characters). Upper and lower case letters are considered different. Variables may not have the same exact name as a keyword.

int i;
char ch;
short temperature;
long population;
float account_balance;

Scope

The scope of a variable is the block in it enclosed in (a block is defined as the code between the curly braces { and }). These are called local variables. Global variables are declared outside of a block. Global variables are viewable in any code after the declaration of the variable. A variable inside a block is recreated each time the block is executed, unless the variable is declared static. Static variables retain their value between calls.

int global_variable;
int function(void)
{
  int local_variable;
  static int static_local;
}

Control

if/else - Conditional execution

if (speed < 65) printf("Speed is OK");
else            printf("Going too fast");

switch/case - Multi-way decisions, when exact values are known. Case statements must use constant values. A break terminates a case. The default case is for any unmatched case.

switch(ch) {
  case 'A': printf("That's an A!\n"); break;
  case 'B': printf("That's a B!\n"); break;
  default:  printf("That's a letter other than A or B.\n");
}

for - a loop typically used when there is a known starting and ending point

// Count from 0 to 9
for (n=0; n<10; n++) {
  printf("n is %d\n",n);
}

while - a loop used to execute code continuously 0 or more times until a condition is met.

// Count backwards from 10 to 1
n = 10;
while (n > 0) {
  printf("n is %d\n",n);
  n--;
}

do/while - a loop used to execute code continuously 1 or more times until a condition is met.

// Print just 0
n = 0;
do {
  printf("n is %d\n",n);
} while(n > 0);

break - used to exit any loop prior to the loop's normal conditional end

while(1) {
  ch = getchar();
  if (ch == '\n') break;
}

continue - start the enclosing loop prior to the normal return-to-start point

while(1) {
  ch = getchar();
  if (ch == ' ') continue; // skip spaces
  printf("You typed: %c\n",ch);
}

goto - jump to a specific place in the code, noted by a unique label.

TOP:
printf("Enter a number between 1 and 10: ");
scanf("%d",&num);
if (num < 1 || num > 10) goto TOP;

Math

+ addition% modulus
- subtraction++ add one
* multiplication= assign to
/ division-- subtract one
n = m + 1;    // n is now the value of m plus one
n = m / 2;    // n is now the value of m divided by two
n--;          // n is now one less than it was before

Mathematical operators may be combined with the assign-to operator to modify the value of a variable in place.

n += 2;  // n is now what it was plus two
n *= 5;  // n is now what it was times five

Constants

A constant is a value that is not a variable. Constants include numbers and letters. 1024 is a numeric constant. 'A' is a character constant. Some special constants include '\n' to mean a newline, and '\t' to mean a tab. Others include '\a' for a beep, '\b' for a backspace, and '\\' for a backslash. A number may be entered in hexadecimal be preceding it with "0x", as in 0x1a2b3c4d. An octal number may be entered by preceding it with a leading zero, as in 0776. Constant floating point numbers should use a decimal point, as in 10.0 or 5.5.

Arrays

An array of variables is a list of variables grouped together with one name. The variables are often related in some way. An array is declared like this: int grades[5]; which declares an array of five ints under the name grades. The elements in the array are addressed as grades[0] through grades[4]. Any data type can be made into an array. Arrays may be multidimensional by including multiple subscripts: int grades[4][5]; might declare an array to store five grades for each of four students.

Comparison

Numeric data (variables or constants) can be compared using the following:

>greater than
<less than
==equal to
>=greater than or equal to
<=less than or equal to
!=not equal to
if (n < 5) printf("n is less than 5\n");
if (n == 5) printf("n is equal to 5\n");
if (n != 5) printf("n is not equal to 5\n");

Logical Operators

Logical operators may be used to string conditional statements together. Use parentheses (the ( and ) characters) to group logical statements.

||logical OR
&&logical AND
!logical NOT
if (age < 0 || age > 130) printf("Invalid age (0 - 130)\n");
if (age >= 0 && age <= 130) printf("Valid age entered\n");

Output

Use the printf library function to output text and data to the user. In its simplest form, used it to output just text:

printf("Very well done.\n"); 
printf("Hello, world!\n");

By combining the printf function with a format and a list of variables, you can output data from a program:

printf("%d",n);
printf("The balance in your account is %.2f\n",balance);

Printf formats

When outputting variables, it is important that the printf function know the type of data you are providing it with. You do this with the printf format. Everything in the format is output as provided until a % sign is seen. After the %, enter a format for the data you wish to print. A format looks like this:

%[flags][width][.precision][prefix]type

flags may be used to modify the data (for example, 0 pads a number on the left with zeroes, + print a number with a sign even if it is positive).

width is the minimum width to print (for example, to print a column of one- and two-digit fields so they line up evenly, specify a 2 for a width)

.precision is the number of decimal places you wish to display if you are printing a float or double value (for example, to print a dollar amount, specify a precision of .2)

prefix is used to modify one of the types (such as h for a short int, l for a long int, and L for double)

type is one of the following:

ccharacter
decimal
ffloating point, in decimal
efloating point, in scientific notation
gin decimal or scientific notation, whichever is shorter

 

%02dprint a number with at least two digits, padding one-digit numbers with a 0
%.2fprint a double number with two decimal places
%cprint a single character

Input

The scanf function can be used to get data from the user. The scanf function uses formats and variable lists much the same way that printf uses them. When presenting scanf with a list of variables to fill, each must be preceded with the & (address of) operator.

scanf("%d",&n);          // Read a number into the n variable
scanf("%f",&amounts[0]); // Read an amount into the 0'th element of the amounts array
scanf("%d%d",&n,&m);     // Read two numbers separated by the ENTER key
scanf("%d %d",&n,&m);    // Read two numbers separated by the ENTER key or a space

The usage of the address-of operator (&) is critical and leaving it off when needed is a common error.

The getchar function may also be used to process user input one character at a time. In this case, though, all data is handled on a character-by-character basis. Getchar may not be used to read a number without proper coding of conversion routines.

Macros

A macro may be used to define an amount or short calculation that never or rarely changes. By using a macro, you save time should the value ever change - you need only change the macro and not each place it is used.

#define PI 3.141
#define STUDENT_COUNT 20

In the first case, every time the value of pi is needed, the macro PI can be used, rather than retyping the number each time it is used. In the second case, the macro STUDENT_TYPE can be used in array declarations, loops, and in other tests and function calls. Should the student count ever change, a small change to the macro propagates the change to all places STUDENT_COUNT is used. Macros differ from variables primarily in that a macro cannot be changed while a program is running.

Functions

Functions allow you to have code to do a specific task that gets repeated many times in just one place. Each time a program needs to perform that task, instead of rewriting the code, the function is called. A function consists of several pieces:

return_value function_name(argument_list);

The return_value tells the compiler what the function sends back to the code that calls it. The return value can be any of the variables types. In addition, functions that do not return any value may return void. The function_name can be any name, following the same conventions as variable names. The argument_list tells the compiler what types of information this function will be receiving.

int area(int height, int width);  // Take the height and width of a rectangle and return its area
float carea(int radius);          // Take the radius of a circle and return its area (in decimal)

The above are "prototypes", used to tell the compiler what a function does and what it expects. A function must be defined before it can be used. A function declaration is its return value, name, and argument list, followed by its definition, denoted by curly braces {}.

int area(int height, int width)
{
  int rect_area = height * width;
  return(rect_area);
}

Each C program has at least one function, called main. The main function is required.

Comments

Two types of comments may typically be used. The oldest is the /* */ comment. Everything between the /* and the */ is a comment, even multiple lines of text. The new way is to use // before a comment. Everything from the // to the end of the line is a comment.

/* this is a comment */
/* this is 
   also a comment */
// and this is a comment, too

Last Modified: 29 Nov 1998