The C Programming Language Torn Apart
Introduction: The evolution and Description of C
The C programming language is a general purpose language which was originally designed for use on the Unix Operating System by Dennis Ritchie. The Unix Operating System, Unix Applications and Tools have been coded in C. This language has evolved from Ken Thompson's B language, which was the language designed for the first Unix System.
C is not a machine specific language and a C program can easily be edited to make it work on various platforms. After the creation of the C programming language, over the years, C became the most preferred language amongst programmers around the world. Due to its immense popularity, many companies developed their own versions of the C compilers, added new features and commands etc This resulted in no specific standard followed by the various programs and led to utter confusion amongst programmers around the world. A need was felt to introduce a standard machine independent code which would be followed by all and make life a lot more easy for programmers. So in 1983 the American National Standards Institute (ANSI) established a committee which aimed at doing just that. This series of manuals too is based on and follows ANSI standards.
C is a high level language. By that what I mean to say is that the C commands or code is written in code which is easily understandable by humans. Its commands are infact plain English words and symbols. As a result C is non machine specific. C is not an interpreted language and unlike Perl a C program has to be first converted into Binary code with the help of a compiler. A compiler does just what the name suggests, compilation i.e. conversion of human understandable code into Binary machine understandable code.
So, even before you can continue reading this manual, you need to get yourself a compiler. To compile C programs, even any C++ compiler would do. If you are a Windows user, then I suggest you get Visual C++, which is a part of Microsoft' s Visual Studio. Although it costs a lot, it is my favorite as it also gives you the benefit of using the MSDN Library. The other good compiler would be Borland C++ 5.5 (available for free download from: http://www.borland.com/bcppbuilder/freecompiler/ ) Then there is DJGPP which is available at:
http://www.delorie.com/djgpp/.If you are running any kind of Unix, then you have a C compiler in your disk itself. You see, the cc and gcc utilities are actually C compilers. For more details, read Carolyn's GTMHH on C, at happyhacker.org
The Standard C Header Library
The ANSI C standard library is an exhaustive collection of pre written routines or functions that are needed by programmers in various applications again and again. Without the functions and routines contained by the header files, a program cannot work properly. Now instead of including the entire code of a long header file in each program , we declare the header files used by the program and reuse the routines contained by them. To understand header files better, read on.
Let us take a practical example to see what actually happens when we try to display a string on the screen. Now to print something on the screen, without using any header file, we need to follow a very complex procedure. Firstly, we would need to extract the string to be printed from the program code, then look for the port in which the Standard Output device is installed, then send the string to that particular port, instructing the Standard Output Device what to do with the string. To write the entire set of above instructions in each C program we develop, would be really cumbersome and inefficient. That is why we use Header Files. With the use of Header Files, we can leave the coding of the entire above procedure to the Header File. With the use of Header Files, we no longer need to know how to communicate with certain Hardware, but instead simply need to know which routine or function to use. Header Files have a .h extension.
The following is a complete list of header files which are a part of the Standard ANSI library-:
<stdio.h> Standard Input \ Output
<assert.h> Diagnostics
<ctype.h> Character Handling
<errno.h> Errors
<float.h> Characteristics of Floating Types
<limits.h> Sizes of Integral Types
<locale.h> Localisation
<math.h> Mathematics
<setjmp.h> Non Local Jumps
<signal.h> Signal Handling
<stdarg.h> Variable Arguments
<stddef.h> Common Definitions
<stdlib.h> Commonly used General Utilities
<string.h> String Handling
<time.h> Date and Time
NOTE: For the Time being, we are only concerned with the Standard I\O header file: stdio.h
Like in the Perl Manual, we will start with the obligatory Hello World program which simply prints the text: Hello World on the screen. It is a big step in a novice's programming career and a person gets immense pleasure if his first program works without any problems.
The following is the source of the Hello World Command. Before I analyze and explain each line of the program, study the program and try to figure out what each line does, then move on to my explanation and see how much you got right. Self Learning can go a very long way.
#include <stdio.h>
main() {
printf ("Hello World \n");
}
Output-:
Hello World
Now let us analyze the code snippet. The first line tells the computer to include information or commands and functions or routines from the header file: stdio.h which is needed to do anything regarding
Input \ Output. The second line defines the function called main. The main function is a special function as it is this function, which by default starts automatically whenever a program is run. [NOTE: Other normal functions can be named anything we want them to be called. We will learn more about functions in upcoming manuals.] The empty brackets, the ( ), after main specify that the function main does not receive any arguments. A function contains certain statements or commands which are executed each time the particular function is called. Now, these statements are enclosed within curly brackets or braces. The '{ }'.
In our first example, the function main has only one statement.
So how does Hello World actually get printed on the screen? Well as soon as the function encounters the function 'printf', it gets the arguments contained by it i.e. the text within the brackets ( ). Then the program calls the printf function in the header file: stdio.h and passes it the values to be printed.
The '\n' is the newline character which causes the Output Cursor to move to the first column of the next row or line. Let us see an example to understand how the newline character works. Say, you want to modify your first C program such that it prints Hello on one line and World on the next line. Then the code would become:
#include <stdio.h>
main () {
printf ("Hello");
printf ("\n");
printf ("World");
}
Output:
Hello
World
Well, actually the same could be achieved with a smaller piece of code:
#include <stdio.h>
main () {
printf ("Hello \n World");
}
Get it? OK, now that you know what the basic structure of a C program is, let us learn some C routines in detail.
The printf Routine: Printing Stuff
The printf routine is a part of the Standard I\O Header file: stdio.h. It helps to display text, numbers and symbols in the specified format on the standard Output Device, which is normally your Monitor.
The general syntax of the printf routine is:
printf ("Characters", ARG1, ARG2…ARGn);
where CHARACTERS is the string to be displayed on the screen. It can have upto 3 distinct escape character sequences, [I have discussed them later in this section.] in any combination. The ARGn is normally a variable whose value is printed on the screen. Confused? Well the following example, ought to clear all your doubts.
Example:
#include <stdio.h>
main () {
printf ("PIE=" , PIE);
}
Assuming that the value of the Variable PIE is 3.14, the output of the above would be:
PIE= 3.14
The following is a complete list of possible escape sequence characters which are a part of ANSI C:
\a Alert Bell
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\\ Backslash
\? Question Mark
\' Single Quote
\" Double Quotes
\ddd Where ddd is an octal number and represents the ASCII code for the number
\xdd Where ddd is a Hexa Decimal number and represents the ASCII code for the number
Examples:
printf ("Is this a VIRUS ALERT \? \a");
will print Is this a VIRUS ALERT ? on the screen and will sound a bell from the CPU Speaker.
printf ("Ankit \t Fadia \n Fadia \t Ankit");
will print the following on the screen:
Ankit Fadia
Fadia Ankit
Formatting your Output using Printf Options
This part might seem a bit weird to grasp, but I assure you, if you read the entire section, you will find it quite easy. You just need to try not give at half stage before reading the entire section.
The general syntax of the printf formatting option is:
%width[.precision] type
where width is the minimum size of the field in which the characters (Output) has to be displayed. It is the number representing the minimum size of the field for displaying the output. The output is right justified unless the width is negative, in which case the output is right aligned. The width does not truncate the output, but accordingly increases its size, to accommodate the output.
The Type can be anything from the below options-:
d, i Decimal Number
o unsigned Octal
x, X unsigned Hexadecimal
u unsigned Decimal Integer
c Single Character
s String
f Floating Point Decimal
g, G Floating Point Number in either fixed decimal or exponential form,
e, E Floating Point Number in Exponential Form
And the precision is the number of places which the output numeral of the Type will have. Like I said before, all this would definitely sound a bit too overwhelming for a complete newbie, but stick with me and keep reading the following examples and I assure you, all your doubts would be cleared.
Examples:
printf ("sum = %10d \n", result);
if the value of the variable result is 145, then the output will be:
sum = 145
In this case, due to the format options we gave, the C program assumes that the value stored by the variable result is a decimal Number [Specified by d] and displays the output i.e. the vale of the variable result in a field of 10 characters wide. [ Specified by %10]. As the width in this example is positive, [10] the output is left aligned. Now let us say if we change the above line of code to the following:
printf ("sum = %-10d \n", result);
then everything else remains the same, only the output instead of being left aligned, is right aligned.
printf ("Percentage = %10.3f", percent);
Assuming that the value of the variable percent is 2.345, the output will be:
Percentage = 2.345
Let's take a bit more complex example which includes escape Sequences.
printf ("\t%2d:%2d %c \n", hours, minutes, time);
Assuming that the value of hours is 11, value of minutes is 45 and the value of time is PM, the output would be:
11:45 PM
Consider the following example:
printf ("%s \t %6.2f \t", item, price);
Assuming that the value of item is CD and the value of price is 100.25, then the output would be:
CD 100.25
Well, till now I am sure almost all of you must be clear in your mind, as to how the printf function can be successfully used. However, if you still have any questions, feel free to contact me.
Gathering Input: The scanf( ) routine
Just like we have the printf( ) function to display output on the screen, we have the scanf( ) function to gather input from the user and to add interactivity to our programs. Before I move on to the syntax and other information on the scanf( ) routine, you need to understand the difference between a variable and the memory location of a variable.
You see, whenever we declare a variable, the C program keeps a part a specific part of the memory for it. Now say we declare a variable and name it ankit and give it the null value i.e. nothing. Now when we give the following print command:
printf ("Ankit's value is: %s", ankit);
then the output would be:
Ankit's value is: NULL
Remember that the variable ankit has been assigned a memory location to store whatever value we want to assign it. Right? Well to refer to this memory location set apart of the variable ankit, we need to make use of the address operator i.e. the & operator. So giving the following command will print the memory address assigned to the variable ankit:
printf ("%s", &ankit);
Now that you know when the address operator is used, let us move on to the basic syntax of the scanf command:
scanf ("Specification", addresses);
where specification is a set of rules which decides the kind of input the program expects the User to type and addresses is a set of memory locations to which the Input is to be stored.
The specification part is nothing but the formatting options which the printf( ) routine has. It decides whether the program is looking for decimals, floating points or characters as input. It also decides the maximum number of characters which can be accepted as input. Basically the syntax of Specification is as follows:
%[width] type
where width specifies the maximum number of characters which can be accepted as input. If the User tries to input more number of characters than specified by width, the program does not accept them and the input cursor does not move ahead.
Type can be anything from the following list of values-:
d, Signed Decimal Number
i Signed Integer whose base(Type of Number System) is decided by the format of the number input:
If the prefix is 0 it expects an octal integer
If prefix is 0x then it expects a Hexadecimal Integer
Else if there is no prefix, then it expects a decimal integer
c Character
s String
o unsigned Octal
x, X unsigned Hexadecimal
u unsigned Decimal Integer
e, f , g Signed Floating Point Value
l This is used to prefix e, f, g and signifies a long integer or unsigned long integer
L This is used to prefix e, f, g and signifies a long double
Let us take some examples to make this routine clearer.
Examples:
scanf ("%d", &pie);
will take a decimal from User Input and store it in the address of the variable ' pie '.
scanf ("%10s", &name);
will take the first 10 characters from the User Input and store them in the address of the variable ' name '.
scanf ("%d%c%lx", &dec, &stringvar, &longvar);
will take a decimal integer, a single character and an unsigned Long Hexadecimal number and assigns them to the addresses of the variables dec, stringvar and longvar.
NOTE: Please, note the Address Operator before the variable name in each of the above examples. Without the use of this operator the program will not work and the variable will not be assigned any value. Somehow, we do not need to use the Address Operator while printing the value stored by a variable. Just remember that while using scanf, you need to use the address operator and with printf, no address operator needs to be used. There is no need to go deep into the reasons behind this.
Wasn't that easy? Well C is not as difficult as it is projected to be and I am sure all experienced C programmers agree with me on that fact. Anyway, till now we have learnt how to print the value stored by a variable and also how to get input from the user and assign it to a variable. But, these routines are of no use if we do not know how to declare variables. In C, we cannot declare and assign values to variables at the same time. You need to first declare a variable and only then can you assign it a value. So let us know learn how to do just that.
Variables
In C, all variables must be declared before they can be used or assigned a value. Variables are usually declared in the beginning of a function i.e. before any executable commands or routines start. A variable declaration is of the following format:
Variable_Type Variable_Name
where Variable_Type is the type is the type of variable, which symbolizes the type of data stored by the declared variable(int, char, float etc) , and Variable_Name is the name of the variable being declared.
A typical variable declaration would be:
int number;
The above line declared a variable by the name number and declared it to store an integer. We can declare more than a single same type of variable in a single line:
int number, number1, number2;
This line declares three Integer variables: number, number1 and number2.
C supports the following basic data types:
int Integer
float Floating Point (Numbers having a fractional Part)
char Single Character (Single Byte like a, b, c etc)
short Short Integer
long Long Integer
double Double Integer
NOTE: The range of int and float varies from system to system. And these are not the only kind of data types. We still have arrays, pointers, structures etc which we will discuss later.
Now, that we have learnt how to declare variables, we need to know how to assign values to them. Well, to assign values to variables, we use the assignment operator, i.e. The ' = ' operator.
For example,
int number;
number = 20;
declares a variable by the name number and type Integer and then the second line assigns it the value 20.
My First Useful Working Program
Now that we know a bit about I\O and also a bit about variables, we are in a position of creating out first useful working C program!!!. This program will ask the user to type the temperature in Fahrenheit and will convert it into Celsius and print the result on the screen. However before we move on, we need to cover a tiny detail: Comments. Anything between a ' /* ' and a ' */ ' is called a comment and is ignored by the compiler. They are inserted so that people find it easier to read the code and understand what each line is meant to do. The following example, has a lot of comments.
#include <stdio.h> /* Include the Standard I/O Header File */
main() { /*Start the Main Function, which is executed automatically */
int fah, cel; /* Declare the (int) variables which will hold the Fahrenheit and Celsius Equivalents */
printf ("Enter Temperature in Fahrenheit:"); /* Hello User. I am hungry, feed me a value */
scanf ("%d", &fah); /* Get the User Input and store it in the address of fah */
cel = (Fah -32) * 5 / 9; /* Get the Grey Cells Working, convert input to Celsius */
printf ("\n \n Temperature in Celsius is….%3d", cel); /* Give User What He wants */
}
Output:
Enter Temperature in Fahrenheit: 32
Temperature in Celsius is…. 0
Wow!!! Wasn't that a kewl program? Well, at least a kewl enough for a C newbie. Anyway, now we come to the Examples Section of the Manual, which consists of a collection of important examples, which make life easier for a newbie C programmer by helping him to learn better. Also comments have been provided where ever necessary.
The following example illustrates the use of all kinds of data types with the printf( ) and scanf( )routines.
#include <stdio.h>
main() {
int inum;
float fnum;
double dnum;
long int lnum;
printf ("Enter An Integer:");
scanf ("%d", &inum);
printf ("Enter a Floating Point Number:");
scanf ("%10f", &fnum);
printf ("Enter a Double Value Number:");
scanf ("%le", &dnum);
printf ("Enter a Hexadecimal unsigned Integer:");
scanf ("%le", &lnum);
printf ("inum = %-5d\n", inum);
printf ("fnum = %10.4f\n", fnum);
printf ("dnum = %15.4e\n", dnum);
printf ("lnum = %lx \n", lnum);
}
Output:
Enter An Integer: 123409
Enter a Floating Point Number: 1.546789
Enter a Double Value Number: 9.879054678E-15
Enter a Hexadecimal unsigned Integer: B543
inum =123409
fnum =1.546789
dnum = 9.879054678E-15
lnum = B543
Remember that I told you that the float and integer value ranges differ from system to system. Now the following program demonstrates how to get and print these ranges. All these ranges are given in the <float.h> and <limits.h> header files, so we need to include them too.
#include <stdio.h>
#include <limits.h>
#include <float.h>
main() {
char char_min, char_max, char_unsigned_max;
int int_min, int_max, int_unsigned_max;
long int long_int_min, long_int_max, long_int_unsigned;
float float_min, float_max;
double double_min, double_max;
char_min = SCHAR_MIN;
char_max = SCHAR_MAX;
char_unsigned_max = UCHAR_MAX;
printf ("Char Min: %d\n", char_min);
printf ("Char Max: %d\n", char_max);
printf ("Char unsigned Max: %u\n\n", char_unsigned_max);
int_min = INT_MIN;
int_max = INT_MAX;
int_unsigned_max = UINT_MAX;
printf ("Int Min: %d\n", int_min);
printf ("Int Max: %d\n", int_max);
printf ("Int unsigned Max: %u\n\n", int_unsigned_max);
long_int_min = LONG_MIN;
long_int_max = LONG_MAX;
long_int_unsigned_max = ULONG_MAX;
printf ("long Int Min: %ld\n", long_int_min);
printf ("long Int Max: %ld\n", long_int_max);
printf ("long Int unsigned Max: %lu\n\n", long_int_unsigned_max);
float_min = FLT_MIN;
float_max = FLT_MAX;
printf ("Float Min: %15.9e\n", float_min);
printf ("Float Max: %15.9e\n\n", float_max);
double_min = DBL_MIN;
double_max = DBL_MAX;
printf ("Double Min: %25.16e\n", double_min);
printf ("Double Max: %25.16e\n\n", double_max);
}
Try out the above program on your machine to find out the ranges of data types(chat, int, float, double, long int) on your system. Well that is all for this week's C manual, see you next time.
Ankit Fadia
ankit@bol.net.in or programmers@techbroker.com http://hackingtruths.tripod.com [The Hacking Truths Archive]