C Study Guide

St. Gabriel's College

|

Variables and Types

Our programs use Variables to remember information.

Data Types

There are four types of Variables that we use very often:

These are the types we will use most often. There are many other types that can be useful. For example, int can only hold 16-bits, so it can only store a number between -32767 and +32767. If we want to store bigger numbers, there are some other types we can use:

Assignment

When we want to store something in a Variable, we can use the Assignment Operator ‘=’ like this:

int age = 23;
float tax_rate = 1.34;
char grade = ‘A’;
char name[1000] = “Chris”;

Typecasting

We can use Typecasting to make one type behave like another type. Let's say we have a floating-point number, but we want to print it out like an integer (with no decimal point), we could do it like this:

float number = 4.125;
printf("Check out this number: %d", (int)number);

This can be useful when you're doing math with floats and ints. If you don't want the floats to be rounded, you can use typecasting to make all of the numbers into floats first:

float n1 = 2.5;
int n2 = 2;
float rounded_result =  n1 + n2; // = 4
float real_result = n1 + (float)n2; // = 4.5

Typecasting is used a lot when we start working with pointers and memory management. For now, just know that you can change a variable's type by casting it as something else.

Make your own Types with typedef

OK, you can't actually make your own types, but with typedef (type define) you can create new names for types that already exist:

typedef float fun_number;

fun_number pi = 3.14159268;

This may not seem too useful now, but it will be very important later when we learn about structs.