Skip to content
ajd98 edited this page Apr 9, 2018 · 20 revisions

Exercise 1: C variables and functions

Like many programming languages, C enables the programmer to include variables, which can represent arbitrary values, and functions, which encapsulate some specific task. The C programming language is specific about the data type of each variable including the return type of a function and the types of a function's arguments. The data type of a variable must be declared before using the variable. Optionally, the value of the variable may be set when the variable is declared. For example, both of the following are valid C:

int a;
a = 5;
int a = 5;

If desired, multiple variables may be declared on a single line:

int a, b, c;

Just as the type of a variable must be declared, so must the type of the return value and parameters of a function be declared:

int
my_func(int a, int b, int c) 
{
  return a + b*c;
}

Data types

C includes a number of built-in data types. The exact definition of each data type may depend on the architecture of the computer and implementation of the compiler; feel free to read the ISO/IEC C standards if you are curious. Take care when choosing a data type that it will behave as you expect. With this caveat in mind, the following table gives some rough rules for common data types:

Data type description
int Signed 16-bit integer (or greater), which can hold values between -215+1 and 215-1 (-32767 and 32767)
char An integer type that can contain the basic character set; typically 8 bits or larger
float A floating point number. Typically 32 bits.
double A floating point number, able to represent at least as many value as float. Typically 64 bits.
void An "empty" data type

Clone this wiki locally