Chapter 6. Basics of Program Writing in Unix/Linux

real coding

Contributed By: Shehrevar Davierwala

The first and most important thing of all, at least for writers today, is
to strip language clean, to lay it bare down to the bone.
—Ernest Hemingway

1. How to start writing program in C using Linux based compiler (gcc/GNU)

Step 1. You can more easily manage things if you create a separate directory for each
program that you’re working on. In this case, we’ll create a directory called hello to
hold our hello program.
On UNIX/Linux type:
% mkdir hello
% cd hello

Step 2. Use your favorite text editor to enter the program. Your file should be named
hello.c

Step 3. [File: hello/hello.c] —-> (don’t write this in program)
#include <stdio.h>
int main()
{
printf(“Hello World\n”);
return (0);
}

Step 4. The compiler takes the source file you’ve just made and converts it into an
executable program. Each compiler has a different command line.

Most UNIX/Linux -based compilers follow the same generic standard. The C compiler is
named cc, and to compile our hello program we need the following command:
% cc -g -ohello hello.c

Note:: The -g option enables debugging. (The compiler adds extra information to the
program to make the program easier to debug.) The switch -ohello tells the
compiler that the program is to be called hello, and the final hello.c is the name
of the source file.

There are several different C compilers for UNIX, so your command line may be
slightly different.

The Free Software Foundation, the GNU people, publish a number of high-quality
programs.

To compile a program using the gcc compiler use the following command line:
% gcc -g -Wall -ohello hello.c
The additional switch -Wall turns on the warnings.
The GNU compiler contains several extensions to the basic C language. If you want
to turn these features off, use the following command line:
% gcc -g -Wall -ansi -pedantic -ohello hello.c
The switch -ansi turns off features of GNU C that are incompatible with ANSI C. The
-pedantic switch causes the compiler to issue a warning for any non-ANSI feature
it encounters.

Step 5. To run the program on UNIX/Linux type:

% hello 

Step 6. Output will appear

Hello World

2. How to make my program more readable ? Should I follow some style?

Some programmers believe that the purpose of a program is only to present the
computer with a compact set of instructions. This concept is not true. Programs
written only for the machine have two problems:
· They are difficult to correct because sometimes even the author does not
understand them.
· Modifications and upgrades are difficult to make because the maintenance
programmer must spend a considerable amount of time figuring out what
the program does from its code. Ideally, a program serves two purposes:

first, it presents the computer with a set of instructions, and second, it
provides the programmer with a clear, easy-to-read description of what the
program does.

Tip 1. A working but uncommented program is a time bomb waiting to explode. Sooner or
later, someone will have to fix a bug in the program, modify it, or upgrade it, and the
lack of comments will make the job much more difficult. A well-commented, simple
program is a work of art. Learning how to comment is as important as learning how
to code properly.

Comments in C start with a slash asterisk (/*) and end with an asterisk slash (*/).

Tip 2. A variable is a place in the computer’s memory for storing a value. C identifies that
place by the variable name. Names can be of any length and should be chosen so
their meanings are clear. (Actually, a length limit exists, but it is so large that you
probably will never encounter it.) Every variable in C must be declared.

The following declaration tells C that
we’re going to use three integer ( int) variables: p, q, and r:
int p,q,r;
But what are these variables for? The reader has no idea. They could represent the
number of angels on the head of a pin or the location and acceleration of a plasma
bolt in a game of Space Invaders. Avoid abbreviations. Exs. abb. are diff. to rd. and
hd. to ustnd. (Excess abbreviations are difficult to read and hard to understand.)
Now consider another declaration:
int account_number;
int balance_owed;

Tip 3. Now we know that we’re dealing with an accounting program, but we could still use
some more information. For example, is the balance_owed in dollars or cents? We should have added a comment after each declaration to explain what we were doing.
For example:
int account_number; /* Index for account table */
int balance_owed; /* Total owed us (in pennies)*/
By putting a comment after each declaration, we, in effect, create a mini-dictionary
where we define the meaning of each variable name. Because the definition of each
variable is in a known place, it’s easy to look up the meaning of a name.
(Programming tools like editors, cross-referencers, and searching tools such as
grep can also help you quickly find a variable’s definition.)

Tip 4. You should take every opportunity to make sure that your program is clear and easy
to understand. Do not be clever. Clever kills. Clever makes for unreadable and
unmaintainable programs. Programs, by their nature, are extremely complex.
Anything that you can to do to cut down on this complexity will make your programs
better. Consider the following code, written by a very clever programmer:

while (‘\n’ != (*p++ = *q++));
It is almost impossible for the reader to tell at a glance what this mess does.
Properly written this should be:
while (1) {
*destination_ptr = *source_ptr;
if (*destination_ptr == ‘\n’)
break; /* Exit the loop if at end of line */
destination_ptr++;
source_ptr++; }

Although the second version is longer, it is much clearer and easier to understand.[3] Even a novice programmer who does not know C well can tell that this program has
something to do with moving data from a source to a destination.

Tip 5In order to make programs easier to understand, most programmers indent their
programs. The general rule for a C program is to indent one level for each new block
or conditional. In our previous example, there are three levels of logic, each with its
own indentation level. The while statement is outermost. The statements inside the
while are at the next level. Finally, the statement inside the if (break) is at the
innermost level.
There are two styles of indentation, and a vast religious war is being raged in the
programming community as to which style is better. The first is the short form:
while (! done) {
printf(“Processing\n”);
next_entry();
}
if (total <= 0) {

printf(“You owe nothing\n”);
total = 0;
} else {
printf(“You owe %d dollars\n”, total);
all_totals = all_totals + total;
}
In this case, curly braces ({}) are put on the same line as the statements. The other
style puts the {} on lines by themselves:

while (! done)
{
printf(“Processing\n”);
next_entry();
}
if (total <= 0)
{
printf(“You owe nothing\n”);
total = 0;
}
else
{
printf(“You owe %d dollars\n”, total);
all_totals = all_totals + total;
}
Both formats are frequently used. You should use the format you feel most
comfortable with.

The amount of indentation is left to the programmer. Two, four, and eight spaces
are common. Studies have shown that a four-space indent makes the code most
readable. However, being consistent in your indentation is far more important than
the indention size you use.
Some editors, like the UNIX Emacs editor, the Turbo C++, Borland C++, and
Microsoft Visual C++ internal editors, contain code that automatically indents your
programs as you create them. Although these editor-based indentation systems are
not perfect, they do go a long way to helping you create properly formatted code.

Tip 6. A program should read like a technical paper. It should be organized into sections
and paragraphs. Procedures form a natural section boundary.

You must organize your code into paragraphs. You should
begin a paragraph with a t opic-sentence comment and separate the comment from
other paragraphs with a blank line. For example:
/* poor programming practice */
temp = box_x1;
box_x1 = box_x2;
box_x2 = temp;
temp = box_y1;
box_y1 = box_y2;
box_y2 = temp;
A better version would be:

/*
* Swap the two corners
*/
/* Swap X coordinate */
temp = box_x1;
box_x1 = box_x2;
box_x2 = temp;
/* Swap Y coordinate */
temp = box_y1;
box_y1 = box_y2;
box_y2 = temp;

Tip 7Your program should be simple. Some general rules of thumb are:
· A single function should not be longer than two or three pages.

If the function gets longer, it can probably be split into two simpler
functions. Th is rule comes about because the human mind can only hold so
much in short-term memory. Three pages are about the most that the
human mind can wrap itself around in one sitting.
Also if your function goes beyond the three -page limit, it probably doesn’t
define a single operation, or probably contains too much detail.

· Avoid complex logic like multiply nested ifs. The more complex your code,
the more indentation levels you will need. When you start running into the right margin, you should consider splitting your code into multiple
procedures, to decrease the level of complexity.
· Did you ever read a sentence, like this one, in which the author went on and
on, stringing together sentence after sentence with the word “and,” and
didn’t seem to understand the fact that several shorter sentences would do
the job much better, and didn’t it bother you? C statements should not go on
forever. Long statements should be avoided. If it looks like an equation or
formula is going to be longer than one or two lines, you should split it into
two shorter equations.
· Finally, the most important rule: make your program as simple and easy to
understand as possible, even if you must break some of the rules. The goal
is clarity, and the rules given in this chapter are designed to help you
accomplish that goal. If they get in the way, get rid of them. I have seen one
program with a single statement that spanned over 20 pages; however,
because of the specialized nature of the program, this statement was simple
and easy to understand.

Class discussion: Create a style sheet for class assignments. Discuss what
comments should go into the programs and why.

Leave a Reply

Your email address will not be published.