C Language
C Language
Description
C is a very powerful language developed at Bell Laboratories in 1970. At the time, UNIX
was written in assembly language which was extremely difficult to debug and maintain.
The developers of UNIX decided that a higher level language than assembly was
required for further development of UNIX. This is how the language C was born.
Throughout the 1970s and 1980s, C continued to evolve growing past its UNIX roots to
finally become an American National Standards Institute (ANSI) standard in 1989.
C has become the basis for many other languages such as C++, Objective C, and
Concurrent C.
C primarily focuses on:
Efficiency - Although C's compiled source code is larger in size than assembly, it
is generally much smaller in size than other languages.
Portability - Due to the core language being ANSI standardized, software written
in ANSI C can generally be compiled and run on machines ranging from PCs to
mainframe computers. It is possible, however, for developers to write nonportable programs if they choose.
One of the biggest strengths of the C language is its standard library. This library
contains hundreds of functions providing string manipulation, input/output and other
utilities that are available to developers on all platforms.
Now let's learn more about the C language.
Description
C programs are written in human readable source code that is not directly executable by
a computer. It takes a three step process to transform the source code into executable
code. These three steps are: Preprocessing, compiling and linking.
Compiling - The modified source code is compiled into binary object code. This
code is not yet executable.
Linking - The object code is combined with required supporting code to make an
executable program. This step typically involves adding in any libraries that are
required.
In most modern compilers, these three activities are handled by a single application
although it is possible to tell the compiler not to do certain functions. (For example, to
compile but not link a program.)
There are a variety of C compilers available for many different platforms. Some
compilers must be purchased and some are free to use. Three of the most common are:
GNU gcc, Clang/LLVM and Microsoft Visual C.
GNU gcc is found on many platforms such as Linux, many flavors of UNIX and
even Windows.
Clang/LLVM is available for all modern Mac OSX systems and many BSD
variants.
We will be using GNU gcc in our examples mainly due to its availability on many
different platforms.
Description
When programming in the C language, these are some of the file extensions that you
will encounter:
File Extension
Type of File
Example
.c
C source file
techonthenet.c
.cc
techonthenet.cc
.cpp
techonthenet.cpp
.o
techonthenet.o
.h
techonthenet.h
.exe
techonthenet.exe
.com
techonthenet.com
This is in contrast to C++ source code files which can and do vary in ending from ".cc"
to".cpp".
For example, you may see the following C++ naming in Microsoft Windows:
> dir
techonthenet.cpp
techonthenet.c
techonthenet.c
Programs in UNIX typically don't have a file extension whereas Microsoft Windows
applications will have either ".com" or ".exe" as their extensions.
For example, this is what you may see in Microsoft Windows:
> dir
techonthenet.exe
Description
The preprocessor will process directives that are inserted into the C source code. These
directives allow additional actions to be taken on the C source code before it is compiled
into object code. Directives are not part of the C language itself.
Preprocessor directives begin with a pound (#) symbol and may have several
arguments.
The following are some of the preprocessor directives that you can use in your source
code:
Directi
ve
Description
Example
#inclu
de
#include
<stdio.h>
#defin
e
#define AGE 50
#undef
#undef AGE
#if
#ifdef
#ifdef SOLARIS
#ifndef
#ifndef WINDOWS
#elif
Directi
ve
Description
Example
10
#else
#else
#endif
#endif
#warni
ng
#error Windows is
an unsupported
platform
#error
Description
In the C Programming Language, the #include directive tells the preprocessor to insert
the contents of another file into the source code at the point where the #include directive
is found. Include directives are typically used to include the C header files for C
functions that are held outsite of the current source file.
Syntax
The syntax for the #include directive in the C language is:
#include <header_file>
OR
#include "header_file"
header_file
The name of the header file that you wish to include. A header file is a C file that
typically ends in ".h" and contains declarations and macro definitions which can
be shared between several source files.
Note
The difference between these two syntaxes is subtle but important. If a header
file is included within <>, the preprocessor will search a predetermined directory
path to locate the header file. If the header file is enclosed in "", the preprocessor
will look for the header file in the same directory as the source file.
Example
Let's look at an example of how to use #include directives in your C program.
In the following example, we are using the #include directive to include
the stdio.h header file which is required to use the printfstandard C library function in
your application.
/* Example using #include directive by TechOnTheNet.com */
#include <stdio.h>
int main()
{
/*
return 0;
}
Header Files
This is a list of the header files that you can include in your program if you want to use
the functions available in the C standard library:
Header File
Type of Functions
<assert.h>
Diagnostics Functions
<ctype.h>
<locale.h>
Localization Functions
<math.h>
Mathematics Functions
<setjmp.h>
<signal.h>
<stdarg.h>
<stdio.h>
Input/Output Functions
Header File
Type of Functions
<stdlib.h>
<string.h>
String Functions
<time.h>
You will find these header files very useful as you become more familiar with the C
language.
Description
In the C Programming Language, the #define directive allows the definition of macros
within your source code. These macro definitions allow constant values to be declared
for use throughout your code.
Macro definitions are not variables and cannot be changed by your program code like
variables. You generally use this syntax when creating constants that represent
numbers, strings or expressions.
Syntax
The syntax for creating a constant using #define in the C language is:
#define CNAME value
OR
#define CNAME (expression)
CNAME
The name of the constant. Most C programmers define their constant names in
uppercase, but it is not a requirement of the C Language.
value
The value of the constant.
expression
Expression whose value is assigned to the constant. The expression must be enclosed
in parentheses if it contains operators.
Note
Do NOT put a semicolon character at the end of #define statements. This is a common
mistake.
Example
Let's look at how to use #define directives with numbers, strings, and expressions.
Number
The following is an example of how you use the #define directive to define a numeric
constant:
#define AGE 10
In this example, the constant named AGE would contain the value of 10.
String
You can use the #define directive to define a string constant.
For example:
#define NAME "TechOnTheNet.com"
In this example, the constant called NAME would contain the value of
"TechOnTheNet.com".
Below is an example C program where we define these two constants:
#include <stdio.h>
int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
return 0;
}
Expression
You can use the #define directive to define a constant using an expression.
For example:
#define AGE (20 / 2)
In this example, the constant named AGE would also contain the value of 10.
Below is an example C program where we use an expression to define the constant:
#include <stdio.h>
int main()
{
printf("TechOnTheNet.com is over %d years old.\n", AGE);
return 0;
}
Description
In the C Programming Language, the #undef directive tells the preprocessor to remove
all definitions for the specified macro. A macro can be redefined after it has been
removed by the #undef directive.
Once a macro is undefined, an #ifdef directive on that macro will evaluate to false.
Syntax
The syntax for the #undef directive in the C language is:
#undef macro_definition
macro_definition
The name of the macro which will be removed by the preprocessor.
Example
The following example shows how to use the #undef directive:
/* Example using #undef directive by TechOnTheNet.com */
#include <stdio.h>
#define YEARS_OLD 12
#undef YEARS_OLD
int main()
{
#ifdef YEARS_OLD
printf("TechOnTheNet is over %d years old.\n", YEARS_OLD);
#endif
return 0;
}
In this example, the YEARS_OLD macro is first defined with a value of 12 and then
undefined using the #undef directive. Since the macro no longer exists, the
statement #ifdef YEARS_OLD evaluates to false. This causes the subsequent printf
function to be skipped.
Here is the output of the executable program:
TechOnTheNet is a great resource.
Description
In the C Programming Language, the #if directive allows for conditional compilation. The
preprocessor evaluates an expression provided with the #if directive to determine if the
subsequent code should be included in the compilation process.
Syntax
The syntax for the #if directive in the C language is:
#if conditional_expression
conditional_expression
Expression that the preprocessor will evaluate to determine if the C source code
that follows the #if directive will be included into the final compiled application.
Note
Example
The following example shows how to use the #if directive in the C language:
/* Example using #if directive by TechOnTheNet.com */
#include <stdio.h>
#define WINDOWS 1
int main()
{
printf("TechOnTheNet is a great ");
#if WINDOWS
printf("Windows ");
#endif
printf("resource.\n");
return 0;
}
Description
In the C Programming Language, the #ifdef directive allows for conditional compilation.
The preprocessor determines if the provided macro exists before including the
subsequent code in the compilation process.
Syntax
The syntax for the #ifdef directive in the C language is:
#ifdef macro_definition
macro_definition
The macro definition that must be defined for the preprocessor to include the C
source code into the compiled application.
Note
Example
The following example shows how to use the #ifdef directive in the C language:
/* Example using #ifdef directive by TechOnTheNet.com */
#include <stdio.h>
#define YEARS_OLD 10
int main()
{
#ifdef YEARS_OLD
printf("TechOnTheNet is over %d years old.\n", YEARS_OLD);
#endif
return 0;
}
A common use for the #ifdef directive is to enable the insertion of platform specific
source code into a program.
The following is an example of this:
/* Example using #ifdef directive for inserting platform specific source code by
TechOnTheNet.com */
#include <stdio.h>
#define UNIX 1
int main()
{
#ifdef UNIX
return 0;
}
In this example, the UNIX source code is enabled. To disable the UNIX source code,
change the line #define UNIX 1 to #define UNIX 0.
Description
In the C Programming Language, the #ifndef directive allows for conditional compilation.
The preprocessor determines if the provided macro does not exist before including the
subsequent code in the compilation process.
Syntax
The syntax for the #ifndef directive in the C language is:
#ifndef macro_definition
macro_definition
The macro definition that must not be defined for the preprocessor to include the
C source code into the compiled application.
Note
Example
The following example shows how to use the #ifndef directive in the C language:
/* Example using #ifndef directive by TechOnTheNet.com */
#include <stdio.h>
#define YEARS_OLD 12
#ifndef YEARS_OLD
#define YEARS_OLD 10
#endif
int main()
{
printf("TechOnTheNet is over %d years old.\n", YEARS_OLD);
return 0;
}
In this example, if the macro YEARS_OLD is not defined before the #ifndef directive is
encountered, it will be defined with a value of 10.
Here is the output of the executable program:
TechOnTheNet is over 12 years old.
If you remove the line #define YEARS_OLD 12, you will see the following output from
the executable program:
TechOnTheNet is over 10 years old.
Description
In the C Programming Language, the #elif provides an alternate action when used with
the #if, #ifdef, or #ifndef directives. The preprocessor will include the C source code that
follows the #elif statement when the condition of the preceding #if, #ifdef or #ifndef
directive evaluates to false and the #elif condition evaluates to true.
The #elif directive can be thought of as #else if.
Syntax
The syntax for the #elif directive in the C language is:
#elif conditional_expression
conditional_expression
Expression that must evaluate to true for the preprocessor to include the C
source code into the compiled application.
Note
Example
The following example shows how to use the #elif directive in the C language:
/* Example using #elif directive by TechOnTheNet.com */
#include <stdio.h>
#define YEARS_OLD 12
int main()
{
#if YEARS_OLD <= 10
printf("TechOnTheNet is a great resource.\n");
#elif YEARS_OLD > 10
printf("TechOnTheNet is over %d years old.\n", YEARS_OLD);
#endif
return 0;
}
This C tutorial explains how to use the #else preprocessor directive in the C language.
Description
In the C Programming Language, the #else directive provides an alternate action when
used with the #if, #ifdef, or #ifndefdirectives. The preprocessor will include the C source
code that follows the #else statement when the condition for the #if, #ifdef, or #ifndef
directive evaluates to false.
Syntax
The syntax for the #else directive in the C language is:
#else
Note
Example
The following example shows how to use the #else directive in the C language:
/* Example using #else directive by TechOnTheNet.com */
#include <stdio.h>
#define YEARS_OLD 12
int main()
{
#if YEARS_OLD < 10
printf("TechOnTheNet is a great resource.\n");
#else
return 0;
}
Description
In the C Programming Language, the #endif directive closes off the following directives:
#if, #ifdef, or #ifndef. When the #endif directive is encountered, preprocessing of the
opening directive (#if, #ifdef, or #ifndef) is completed.
Syntax
The syntax for the #endif directive in the C language is:
#endif
Example
The following example shows how to use the #endif directive in the C language:
/* Example using #endif directive by TechOnTheNet.com */
#include <stdio.h>
#define WINDOWS 1
int main()
{
printf("TechOnTheNet is a great ");
#if WINDOWS
printf("Windows ");
#endif
printf("resource.\n");
return 0;
}
Description
Syntax
The syntax for the #warning directive in the C language is:
#warning message
message
The message to output prior to continuing preprocessing.
Example
Let's look at how to use #warning directives in your C program.
The following example shows the output of the #warning directive:
/* Example using #warning directive by TechOnTheNet.com */
#include <stdio.h>
int main()
{
/* The age of TechOnTheNet in seconds */
int age;
#warning The variable age may exceed the size of a 32 bit integer
return 0;
}
When compiling this program, the preprocessor will output the following warning:
warning: The variable age may exceed the size of a 32 bit integer
Since this is a #warning directive, the program compilation continues and we can
execute the program to see its output.
Here is the output of the executable program:
TechOnTheNet is 378432000 seconds old
Description
In the C Programming Language, the #error directive causes preprocessing to stop at
the location where the directive is encountered. Information following the #error directive
is output as a message prior to stopping preprocessing.
Syntax
The syntax for the #error directive in the C language is:
#error message
message
Message to output prior to stopping preprocessing.
Example
Let's look at how to use #error directives in your C program.
The following example shows the output of the #error directive:
/* Example using #error directive by TechOnTheNet.com */
#include <stdio.h>
#include <limits.h>
/*
* Calculate the number of milliseconds for the provided age in years
* Milliseconds = age in years * 365 days/year * 24 hours/day, 60 minutes/hour,
60 seconds/min, 1000 millisconds/sec
*/
#define MILLISECONDS(age) (age * 365 * 24 * 60 * 60 * 1000)
int main()
{
/* The age of TechOnTheNet in milliseconds */
int age;
return 0;
}
In this example, we are using the int data type to hold the age of TechOnTheNet in
milliseconds. The int data type has a maximum value of INT_MAX which is defined in
the limits.h header file and holds a value of 2^31 - 1 on both 32 and 64 bit systems.
(See here for other variable types and their sizes.)
The statement #if INT_MAX < MILLISECONDS(12) evaluates whether or not the int
data type is large enough to store the age in milliseconds. If it is not, the processor will
output the following error message:
error: Integer size cannot hold our age in milliseconds
Since an error occurred, the program compilation will not complete and therefore no
executable program will be created.
A typical use of the #error directive is to prevent compilation if a known condition exists
that would cause the program to not function properly if the compilation completed. (For
example, the C source was designed for a specific platform and was being compiled on
an incompatible platform.)
C Language: Comments
This C tutorial explains how to use comments in the C language with syntax and
examples.
Description
In the C Programming Language, you can place comments in your source code that are
not executed as part of the program.
Comments provide clarity to the C source code allowing others to better understand
what the code was intended to accomplish and greatly helping in debugging the code.
Comments are especially important in large projects containing hundreds or thousands
of lines of source code or in projects in which many contributors are working on the
source code.
A comment starts with a slash asterisk /* and ends with a asterisk slash */ and can be
anywhere in your program. Comments can span several lines within your C program.
Comments are typically added directly above the related C source code.
Adding source code comments to your C source code is a highly recommended
practice. In general, it is always better to over comment C source code than to not add
enough.
Syntax
The syntax for a comment is:
/* comment goes here */
OR
/*
* comment goes here
*/
Note
C++ introduced a double slash comment prefix // as a way to comment single lines. The
following is an example of this:
// Author: TechOnTheNet.com
This form of commenting may be used with most modern C compilers if they also
understand the C++ language.
The compiler will assume that everything after the /* symbol is a comment until it
reaches the */ symbol, even if it spans multiple lines within the C program.
OR
#define AGE 6
In these examples, the compiler will define a constant called AGE that contains the
value of 6. The comment is found at the end of the line of code after the constant has
been defined.
C Language: Variables
This C tutorial explains how to declare variables in the C language.
Description
In the C Programming Language, variables are used to store various types of data.
Variables must be defined before they can be used within a program. Variable
declarations include the type of the variable and, optionally, its initial value.
Syntax
The syntax for declaring a variable in the C language is:
c_type variable_name1 [= value1];
Additional variables of the same C type can be declared by comma separating the
variables as follows:
c_type variable_name1 [= value1] [, variable_name2 [= value2], ...
variable_name_n [= value_n]];
Syntax Definitions
c_type
The type of the variable being declared. Refer to the Types section below for a list of the
common C types.
variable_name1
The name of the first variable to declare.
value1
Optional. If provided, it is the value to assign to variable_name1.
variable_name2, ... variable_name_n
Optional. These are additional variables that will be declared with the same C type.
value2, ... value_n
Optional. These are the values that you wish to assign
to variable_name2 through variable_name_n.
Note
Constant Variable
To define a constant variable, you can place the keyword const in front of the declaration
as follows:
const c_type variable_name1 [= value1];
Variables defined as constants can not be changed after their initial value is set.
Types
The following is a table of the most common variable types used in C. The min and max
values are based on a 32-bit system:
C Type
Variable Type
Typically Holds
Min Value
Max Value
signed
char
Signed
Character
-128
127
unsigned
char
Unsigned
Character
255
short int
Short Integer
-32,768
32,767
unsigned
short int
Unsigned
Short Integer
Unsigned 16 bit
Integer number
65,535
C Type
Variable Type
Typically Holds
Min Value
Max Value
int
Integer
2,147,483,
648
2,147,483,
647
unsigned
int
Unsigned
Integer
Unsigned 32 bit
Integer number
4,294,967,
295
long int
Signed Long
Integer
2,147,483,
648
2,147,483,
647
unsigned
long int
Unsigned
Long Integer
Unsigned 64 bit
Integer number
4,294,967,
295
float
Float
Single precision
floating point number
1.17 x 10-38
3.4 x 1038
double
Double
Double precision
floating point number
2.2 x 10-308
1.79 x 10308
TIP: Variable min/max values may vary from system to system. To find the appropriate values
for your system, locate and refer to the limits.h C header file on your system.
Let's take a closer look at how to define and use each of these C variable types.
Description
short int
int
unsigned int
long int
For the purposes of this tutorial, we will focus on the basic int type.
Syntax
The syntax for declaring integer variables is:
int variable_name1 [= value1];
Syntax Definitions
variable_name1
The name of the first variable to declare.
value1
Optional. If provided, it is the value to assign to variable_name1.
variable_name2, ... variable_name_n
Optional. These are additional variables that will be declared with the same C type.
value2, ... value_n
To declare an integer variable with a type other than int, simply replace the int keyword
in the syntax above with your selected type.
For example:
short int variable_name1 [= value1];
int main()
{
int age;
age = 10;
printf("TechOnTheNet.com is over %d years old.\n", age);
return 0;
}
In this example, the variable named age would be defined as an integer and assigned
the value of 10.
Below is an example C program where we declare this variable and assign the value:
#include <stdio.h>
int main()
{
int age = 10;
return 0;
}
In this example, two variables called age and reach would be defined as integers.
Below is an example C program where we declare these two variables:
#include <stdio.h>
int main()
{
int age, reach;
age = 10;
reach = 100;
printf("TechOnTheNet.com is over %d years old and reaches over %d
countries.\n", age, reach);
return 0;
}
This C program would print "TechOnTheNet.com is over 10 years old and reaches over
100 countries."
In this example, two variables called age and reach would be defined as integers and be
assigned the values 10 and 100, respectively.
Below is an example C program where we declare these two variables and assign their
values:
#include <stdio.h>
int main()
{
int age = 10, reach = 100;
return 0;
}
This C program would print "TechOnTheNet.com is over 10 years old and reaches over
100 countries."
Syntax
The syntax for declaring a float variable is:
Syntax Definitions
variable_name1
The name of the first variable to declare.
value1
Optional. If provided, it is the value to assign to variable_name1.
variable_name2, ... variable_name_n
Optional. These are additional variables that will be declared with the same C type.
value2, ... value_n
Optional. These are the values that you wish to assign
to variable_name2 through variable_name_n.
int main()
{
float age;
age = 10.5;
printf("TechOnTheNet.com is over %f years old.\n", age);
return 0;
}
In this example, the variable named age would be defined as a float and assigned the
value of 10.5.
Below is an example C program where we declare this variable and assign the value:
#include <stdio.h>
int main()
{
float age = 10.5;
return 0;
}
In this example, two variables called age and load would be defined as float.
Below is an example C program where we declare these two variables:
#include <stdio.h>
int main()
{
float age, load;
age = 10.5;
load = 1.4;
printf("TechOnTheNet.com is over %f years old and pages load in %f
seconds.\n", age, load);
return 0;
}
This C program would print "TechOnTheNet.com is over 10.500000 years old and pages
load in 1.400000 seconds."
In this example, two variables called age and load would be defined as float and be
assigned the values 10.5 and 1.4, respectively.
Below is an example C program where we declare these two variables and assign their
values:
#include <stdio.h>
int main()
{
float age = 10.5, load = 1.4;
return 0;
}
This C program would print "TechOnTheNet.com is over 10.500000 years old and pages
load in 1.400000 seconds."
/*
* Every program requires a main function
* This is the function the system will call when executing the program
* In this example, we will leave out the usual arguments which are passed to
main
*/
int main()
{
/* Display our message */
printf("Hello TechOnTheNet!\n");
You will need a C compiler installed on your computer to compile the application. For the
purposes of this example, we will assume that you are using a UNIX system with the
GNU C compiler (gcc) installed.
Compilers can have very different options and interfaces so please consult the
documentation for the version you are using.
To compile this application using gcc you would type:
gcc hello.c -o hello
Since this is a very basic example, we do not need to provide any additional libraries or
information to gcc.
The result will be an executable file named hello that can be run by typing:
./hello