Navigator Bar

Sunday, 27 March 2011

Writing Our First C Program

In "Getting Started C" we learned that C is a high-level programming language and that we need a C compiler to translate our C programs into binary code that our computer can understand and execute.

In this lesson we'll learn to write our first C program and the basics of a C program, such as :

* The #include directive
* Header files
* Comments
* The main() function
* The return statement
* The exit() function
* The newline character (\n)
* The void data type
* Translating a C program into an executable file
* Debugging

A Simple C Program

Let's have a look at our first C program, demonstrated in below form. Later, we're going to write our own C program for the first time.

TYPE
A simple C program.

1: /* 02L01.c: This is my first C program */
2: #include
3:
4: main()
5: {
6: printf ("Howdy, neighbor! This is my first C program.\n");
7: return 0;
8: }

This is a very simple C program, which is saved in a file called 02L01.c. Note that the name of a C program file must have an extension of .c. If we've installed a C compiler and set up the proper development environment, we should be able to compile this C program and make it into an executable file.

We can set up our development environment in such a way that all C programs can be compiled and made into DOS-based applications. For instance, 02L01.exe is the name of the DOS application made from 02L01.c. Note that .exe is included as the extension to the name of a DOS application program (that is, an executable file).

Also, on our machine, we can save all the executable files made from the C programs into a dedicated directory called C:\app. Therefore, if we type in 02L01 from a DOS prompt and press the Enter key, we can run the 02L01.exe executable file and display the message Howdy, neighbor! This is our first C program. on the screen. The following output is a copy from the screen:

C:\app> 02L01
Howdy, neighbor! This is my first C program.
C:\app>

Comments

Now let's take a close look at the C program in our first C program.

The first line contains a comment:

/* 02L01.C: This is my first C program */

We notice that this line starts with a combination of a slash and an asterisk, /*, and ends with */. In C, /* is called the opening comment mark, and */ is the closing comment mark. The C compiler ignores everything between the opening comment mark and closing comment mark. That means the comment in the first line of Listing 2.1, 02L01.C: This is my first C program, is ignored by the compiler.

The only purpose of including comments in our C program is to help us document what the program or some specific sections in the programs do. Remember, comments are written for programmers like us. For example, when we read someone's code, the comments in the code help us to understand what the code does, or at least what the code intends to do.

We don't need to worry about the size or performance speed of our C program if we add many comments into it. Adding comments into a C program does not increase the size of the binary code of the program (that is, the executable file), although the size of the program itself (that is, the source code) may become larger. Also, the performance speed of the executable file made from our C program is not affected by the comments inside our C program.

Most C compilers allow us to write a comment that crosses more than one line. For instance, we can write a comment in C like this:

/*
This comment does not increase the size of
the executable file (binary code), nor does
it affect the performance speed.
*/

which is equivalent to this:

/* This comment does not increase the size of */
/* the executable file (binary code), nor does */
/* it affect the performance speed. */

NOTE

These days, there is another way to put comments into a C program. C++ started using two slashes (//) to mark the beginning of a comment line; many C compilers now use this convention as well. The comment ends at the end of the line. For instance, if I write a C program in Borland C++ or Visual C++, the following two comments are identical:

/*
This comment does not increase the size of
the executable file (binary code), nor does
it affect the performance speed.
*/
// This comment does not increase the size of
// the executable file (binary code), nor does
// it affect the performance speed.

Note that this new style of using // as the beginning mark of a comment has not been approved by ANSI. Make sure our C compiler supports // before we use it.

One thing that needs to be pointed out is that the ANSI standard does not support nested comments, that is, comments within comments. For instance, the following is not allowed by the ANSI standard:

/* This is the first part of the first comment
/* This is the second comment */
This is the second part of the first comment */

TIP

We can use the opening comment mark, /*, and closing comment mark, */, to help us test and fix any errors found in our C program. We can comment out one or more C statements in our C program with /* and */ when we need to focus on other statements and watch their behaviors closely. The C compiler will ignore the statements we comment out.

Later, we can always restore the previously commented-out statements simply by removing the opening comment and closing comment marks. In this way, we don't need to erase or rewrite any statements during the testing and debugging.

The #include Directive

Let's now move to line 2 in the C program of our First C program:

#include

We see that this line starts with a pound sign, #, which is followed by include. In C, #include forms a preprocessor directive that tells the C preprocessor to look for a file and place the contents of the file in the location where the #include directive indicates.

The preprocessor is a program that does some preparations for the C compiler before our code is compiled.

Also in this line, we see that follows #include. we may guess that the file the #include directive asks for is something called stdio.h. We are exactly right! Here, the #include directive does ask the C preprocessor to look for and place stdio.h where the directive is in the C program.

The name of the stdio.h file stands for standard input-output header file. The stdio.h file contains numerous prototypes and macros to perform input or output (I/O) for C programs.


NOTE


The C programming language distinguishes between loourcase and uppercase characters. In other words, C is a case-sensitive language. For instance, stdio.h and STDIO.H are different filenames in C. Likewise, main() and Main() are two different function names.

Header Files

The files that are required by the #include directive, like stdio.h, are called header files because the #include directives are almost always placed at the head of C programs. Actually, the extension name of .h does mean "header."

Besides stdio.h, there are more header files, such as stdlib.h, string.h, math.h, and so on. Appendix A, "ANSI Standard Header Files," gives a list of all the ANSI standard header files.

Angle Brackets (< >) and Double Quotes (" ")

In the second line of our First C program, there are two angle brackets, < and >, that are used to surround stdio.h. We may be wondering what the angle brackets do. In C, the angle brackets ask the C preprocessor to look for a header file in a directory other than the current one.

For instance, the current directory containing the 02L01.C file is called C:\code on our computer. Therefore, the angle brackets around tell the C preprocessor to look for stdio.h in a directory other than C:\code.

If we want to let the C preprocessor look into the current directory first for a header file before it starts to look elsewhere, we can use double quotes to surround the name of the header file. For instance, when the C preprocessor sees "stdio.h", it looks in the current directory, which is C:\code on our machine, first before it goes elsewhere for the stdio.h header file.

Normally, the header files are saved in a subdirectory called include. For instance, we might install a Microsoft C compiler in the directory MSVC on our hard drive, which is labeled as the C drive. Then the path to access the header files becomes C:\MSVC\include.

The main() Function

In line 4 of our First C program, we see this function:

main ()

This is a very special function in C. Every C program must have a main() function, and every C program can only have one main() function.

We can put the main() function wherever we want in our C program. However, the execution of our program always starts with the main() function.

In Our First C program, the main() function body starts in line 4 and ends in line 8. Because this is a very simple program, the main() function is the only function defined in the program. Within the main() function body, a C library function, printf(), is called in order to print out a greeting message.

One more important thing about main() is that the execution of every C program ends with main(). A program ends when all the statements within the main() function have been executed.

The Newline Character (\n)

In the printf() function, one thing worth mentioning at this moment is the newline character, \n. Usually suffixed at the end of a message, the newline character tells the computer to generate a carriage-return and line-feed sequence so that anything printed out after the message will start on the next new line on the screen.

Exercise 3 in this lesson gives us a chance to use the newline character to break a one-line message into two lines.

The return Statement

All functions in C can return values. For instance, when we make a function to add two numbers, we can make such a function that returns to us the value of the addition.

The main() function itself returns a value. By default, main() returns an integer. In C, integers are decimal numbers without fraction portions.

Therefore, in line 7 of our First C program, there is a statement, return 0;, that indicates that 0 is returned from the main() function and the program is terminated normally.

A nonzero value returned by the return statement tells the operating system that an error has occurred. The bigger the return value, the more severe the error.

The exit() Function

There is also a C library function, exit(), that can be used to cause a program to end. Because the exit() function is defined in a header file, stdlib.h, we have to include the header file at the beginning of our program.

Unlike main(), the exit() function itself does not return any values, but the argument to exit() indicates whether the program is terminated normally. A nonzero argument to the exit() function tells the operating system that the program has terminated abnormally.

Actually, we can replace return 0; in line 7 of our First C program with exit(0); and get a similar result after running the modified program.

Note that return and exit() can also be used in other functions.

C program above contains the program that uses exit() instead of return.

TYPE this
A C program with exit().


1: /* 02L02.c */
2: #include
3: #include
4:
5: void main()
6: {
7: printf ("Howdy, neighbor! This is my first C program.\n");
8: exit(0);
9: }

After compiling the program above, we should be able to run the program and get the same message, Howdy, neighbor! This is my first C program., printed out on the screen.

The void Data Type
We may notice that the void word has been added into the C program aboce. void is a keyword for a data type in C. When a void is placed prior to a function name, it indicates that the function does not return a value.

As we have learned, the exit() function does not return any values, but, by default, the main() function does. Therefore, as shown in line 5 of C program above, void is used to modify the returning data type of main() and to make the main() function not return any value.

Compiling and Linking

We may already be anxious to know how an executable file is made. Let's have a look at how a C program is compiled and translated into an executable file (binary code). There are at least three steps needed to create an executable file.

First, a program written in C, called source code, is made. Then the source code is compiled by a C compiler, which creates a new file. The new file is an object file. In the UNIX operating system, the name of an object file ends with the extension .o; in the DOS operating system, the extension is .obj.

We cannot execute the object file because there is some function code missing. We have to finish the next step: linking. Linking is done by invoking a special program called a linker, which normally comes with the compiler package.

A linker is used to link together the object file, the ANSI standard C library, and other user-generated libraries to produce an executable file—the binary code. In this stage, the binary code of the library functions that are called in the source code is combined with the object file; the result is saved into a new file—an executable file. As we learned in the first hour of this book, the name of an executable file usually ends with the extension .exe in DOS.

(.com is another extension used for a DOS executable filename.) In UNIX, it's not necessary to include such an extension to an executable filename.

Later, we'll learn that in many cases, there may be several object files that have to be linked together in order to make an executable program.

Note that the object file and executable file are both machine-dependent. We cannot simply move an executable file, without recompiling the source code, from the current computer platform to another one that is operated by a different operating system even though the source code of the executable file, presumably written in ANSI C, is machine independent (that is, portable).

What's Wrong with My Program?

When we finish writing a C program and start to compile it, we might get some error or warning messages. Don't panic when we see error messages. We're human beings. Everybody makes mistakes. Actually, we should appreciate that our compiler catches some errors for we before we go any further.

Usually, our compiler can help we check the grammar of our C program and make sure we've followed the C programming rules properly. For instance, if we forget to put the ending brace on the main() function in line 8 of our first C program, we'll get an error message something like this: syntax error : end of file found.

Also, the linker will issue an error message if it cannot find the missing code for a needed function in the libraries. For instance, if we misspell printf() as pprintf() in the program of our first C program, we'll see an error message: `_pprintf': unresolved external (or something similar).

All errors found by the compiler and linker must be fixed before an executable file (binary code) can be made.

Debugging our Program

In the computer world, program errors are also called bugs. In many cases, our C compiler and linker do not find any errors in our program, but the result generated by running the executable file of the program is not what we expect. In order to find those "hidden" errors in our program, we may need to use a debugger.

Normally, our C compiler vendor already includes a debugger software program in the C compiler package. The debugger can execute our program one line at a time so that we can watch closely what's going on with the code in each line, or so that we can ask the debugger to stop running our program on any line.


SOURCE LINK
Read More..

Tuesday, 22 March 2011

Getting Started C


In this first lesson we'll learn the following:

    * What C is
    * Why we need to learn C
    * The ANSI standard
    * Hardware and software required in order to run the C program

What Is C?


C is a programming language. The C language was first developed in 1972 by Dennis Ritchie at AT&T Bell Labs. Ritchie called his newly developed language C simply because there was a B programming language already. (As a matter of fact, the B language led to the development of C.)

C is a high-level programming language. In fact, C is one of the most popular general-purpose programming languages.
In the computer world, the further a programming language is from the computer architecture, the higher the language's level. We can imagine that the lowest-level languages are machine languages that computers understand directly. The high-level programming languages, on the other hand, are closer to our human languages.

High-level programming languages, including C, have the following advantages:

    * Readability: Programs are easy to read.
    * Maintainability: Programs are easy to maintain.
    * Portability: Programs are easy to port across different computer platforms.

The C language's readability and maintainability benefit directly from its relative closeness to human languages, especially English.
Each high-level language needs a compiler or an interpreter to translate instructions written in the high-level programming language into a machine language that a computer can understand and execute. Different machines may need different compilers or interpreters for the same programming language. For instance, we use Microsoft's C compiler to compile the C programs for our personal computer (PC). If we need to run the C programs on a UNIX-based workstation, We have to use another type of C compiler to compile these programs. Therefore, the portability of programs written in C is realized by re-compiling the programs with different compilers for different machines.

The Computer's Brain
We may know that the brain of a computer is the central processing unit (CPU). Some computers may have more than one CPU inside. A CPU has millions of transistors that make use of electronic switches. The electronic switches have only two states: off and on. (Symbolically, 0 and 1 are used to represent the two states.) Therefore, a computer can only understand instructions consisting of series of 0s and 1s. In other words, machine-readable instructions have to be in binary format.

However, a computer program written in a high-level language, such as C, Java, or Perl, is just a text file, consisting of English-like characters and words. We have to use some special programs, called compilers or interpreters, to translate such a program into a machine-readable code. That is, the text format of all instructions written in a high-level language has to be converted into the binary format. The code obtained after the translation is called binary code. Prior to the translation, a program in text format is called source code.

The smallest unit of the binary code is called a bit (from binary digit), which can have a value of 0 or 1. 8 bits make up one byte, and half a byte (4 bits) is one nibble.

In addition, the C language has other advantages. Programs written in C can be reused. We can save your C programs into a library file and invoke them in our next programming project simply by including the library file. C is a relatively small programming language, which makes life easier for us. We don't have to remember many C keywords or commands before we start to write programs in C to solve problems in the real world.
For those who seek speed while still keeping the convenience and elegance of a high-level language, the C language is probably the best choice. In fact, C allows us to get control of computer hardware and peripherals. That's why the C language is sometimes called the lowest high-level programming language.
Many other high-level languages have been developed based on C. For instance, Perl is a popular programming language in World Wide Web (WWW) design across the Internet. Perl actually borrows a lot of features from C. If we understand C, learning Perl is a snap. Another example is the C++ language, which is simply an expanded version of C, although C++ makes object-oriented programming easier. Also, learning Java becomes much easier if we already know C.

    NOTE :


    There are two types of programming languages:compiled language and interpreted language.


    A compiler is needed to translate a program written in a compiled language into machine-understandable code (that is, binary code) before we can run the program on our machine. When the translation is done, the binary code can be saved into an application file. We can keep running the application file without the compiler unless the program (source code) is updated and we have to recompile it. The binary code or application file is also called executable code (or an executable file).


    On the other hand, a program written in an interpreted language can be run immediately after we finish writing it. But such a program always needs an interpreter to translate the high-level instructions into machine-understandable instructions (binary code) at runtime. We cannot run the program on a machine unless the right interpreter is available.


    We can think of the C language as a compiled language because most

    C language vendors make only C compilers to support programs written in C.


C and the ANSI Standard

For many years, the de facto standard for the C programming language was the K&R standard because of the book The C Programming Language, written by Brian Kernighan and Dennis Ritchie in 1978. However, there were many changes unofficially made to the C language that were not presented in the K&R standard.
Fearing that C might lose its portability, a group of compiler vendors and software developers petitioned the American National Standards Institute (ANSI) to build a standard for the C language in 1983. ANSI approved the application and formed the X3J11 Technical Committee to work on the C standard. By the end of 1989, the committee approved the ANSI standard for the C programming language.
The ANSI standard for C enhances the K&R standard and defines a group of commonly used C functions that are expected to be found in the ANSI C standard library. Now, all C compilers have the standard library, along with some other compiler-specific functions.


Setting Up Our System
Basically, we need a computer and a C compiler in order to compile and run our own C programs. The recommended hardware and software are listed in the following sections.

Hardware
Any type of computer that has or can access a C compiler is fine. (The C compiler should support the ANSI standard.) More likely, we may have a PC on our desktop. A 286 PC with a 50MB hard drive and 1MB memory (RAM) is probably the minimum requirement to run a DOS-based C compiler. For a Windows-based C compiler, we must have a bigger hard drive and add more memory to our computer.

Software
If we're using a UNIX-based workstation, we might already have a C compiler loaded

on our machine, or at least we might be able to access a C compiler on a server machine. Check with our system administrator to find out about a C compiler that supports the ANSI standard, and set up the right path to access it. On a UNIX-based machine, we should know how to use a text editor, such as vi and emacs, to write C programs.

If you have a PC, we need to install a C compiler and a text editor on it. Most C compilers come with an editor. We can also use a text editor that is already installed on our machine.

Borland International's Turbo C and Microsoft's Quick C used to be very popular in the C compiler market. These days, C compiler vendors like to bundle C and C++ compilers together. For instance, Borland International sells Borland C++ with a C compiler. The same thing is true for Microsoft's Visual C++. Both Borland C++ and Visual C++ support the ANSI standard. Both of them provide an integrated development environment (IDE), which we can use to edit your C programs, along with other fancy features for advanced Windows programming.

Appendix D, "Some Popular Commercial C/C++ Compilers," introduces several C compilers besides Borland C++ and Microsoft's Visual C++.

We can pick up any C compiler we like, as long as the compiler supports the ANSI standard. Most C/C++ compilers provide a quick tutorial that shows us how to install the compiler and set up a development environment on our computer.

SOURCE LINK

Read More..