Showing posts with label C preprocessor. Show all posts
Showing posts with label C preprocessor. Show all posts

Friday, January 6, 2012

What is the complete structure of format specifications for int and float type data?

The complete structure of format specifications is

%[flag][field width][.precision]type

where format string components enclosed by [ ] are optional (the characters [ and ] are not the part of the format string.

The meanings of these components may vary slightly from compiler to compiler. Therefore, you should check the manual of the compiler you use.

Thursday, January 5, 2012

How does the preprocessor work with a define directive?

The form of a define directive is

#define symbolic_name replacement

or

#define DAYS_IN_YEAR 365

where symbolic_name is the name of the constant macro that we are creating and replacement is the value with which we want symbolic_name replaced. The word define must be completely in lower case. On being instructed by a define directive, the preprocessor replaces any symbolic_name (excluding those that appear in comments or in string literals) in the program with the given replacement. For example, the symbolic name DAYS_IN_YEAR in the statement

printf("Days in year=%5d\n",DAYS_IN_YEAR);

is replaced by 365 before the program is translated into machine language. In other words, the preceding statement will be "rewritten" by the preprocessor to be

printf("Days in year=%5d\n,365);

prior to the compiler translating the code into machine language. In this example, the constant macro (DAYS_IN_YEAR) is replaced with the value 365 throughout the program by the preprocessor before the program is compiled.

Note that only one constant macro can be defined per line. The constant macro cannot be placed on the left side of an assignment statement, meaning that we cannot try to assign a new value to the constant macro at a later point in the program. You can understand why this does not work if you think about the operation involved. For instance, if we wanted to write

DAYS_IN_YEAR = 365.25

as an assignment statement in our program, the preprocessor would convert this to be

365 = 365.25

before the source code is translated into object code. This statement clearly makes no sense and therefore illustrates why we cannot use a constant macro on the left side of an assignment statement. Therefore, it is said that a constant macro is not an lvalue (pronounced "ell value"), meaning it cannot go on the left side of an assignment statement. A constant macro is considered to be an rvalue (pronounced "are value"), meaning that it can go on the right side of an assignment statement bu not the left.

How do I create a constant macro?

We use a preprocessor directive to create a constant macro. The preprocessor is a system program that is part of the C compiler. It automatically performs various operations prior to the translation of source code into object code. In C, preprocessing directives begin with the # symbol (which must begin the line). A semicolon must not be used at the end of the preprocessing directive. Only the preprocessing directive should be on the line. For example, the line

#define DAYS_IN_YEAR 365

is a preprocessor directive called a define directive.

Wednesday, January 4, 2012

What is debugging?

In your source code, looking for and correcting errors or mistakes that cause your programs to behave unexpectedly is called debugging. In general, there are three types of errors in a C source code: syntax errors, run-time errors, and logic errors.

Syntax errors are mistakes cause by violating the "grammar" rules of C. They easily can be caused by typographical mistakes or a lack of knowledge of the forms of statements required by C. These errors often can be diagnosed by the C compiler as it compiles the program. If your computer indicates errors when your try to compile a program, it will not translate your code into machine instructions. You must fix the errors before the compiler will translate your code. Therefore, when you have syntax errors you will not generate any output, even if your syntax errors are very minor and located in the very last lines of code.

Run-time errors, also called semantic errors or smart errors, are caused by violation of the rules during execution of your program. The compiler does not recognize them during compilation. However, the computer displays a message during execution that something has gone wrong and (usually) that execution is terminated. If a run-time error occurs near the end execution, you may get some of your results. The error message given by the computer may help you locate the source of error in your code.

Logic errors are the most difficult errors to recognize and correct, because the computer does not indicate that there are errors in your program as it does with syntax and run-time errors. It is up to you to identify that there is a problem at all. It is up to you to look at your output and decide that it is incorrect. In other words, your program may have appeared to have executed successfully, perhaps giving very reasonable results. However, the answer maybe completely wrong. You must recognize that they are wrong and correct code in the program. (Be careful though. Many hours have been spent looking for bugs in programs only to find out that the program is correct, but the input data is incorrect.)

How do we concatenate (which means to connect) a C string literal?

Here, we illustrate three methods. In method 1, we use a backslash at the end of a line to indicate that a string literal has not finished and continues on the next line. Since the C compiler disregards all blank characters behind a statement, the connection to the next line will start right at the end of the preceding statement. If you want to include blank characters in a statement that occupies two lines, either place them before the backslash in the first lines or at the beginning of the second line. For example, the statement

printf("Welcome to New \
York!");

is equivalent to

printf("Welcome to New York!");

but not

printf("Welcome to New York!");


In method 2, we enclose each unfinished string literal in double quotes; for example, the statement

printf("From " "Russia "
"with" " love.\n");

is equivalent to the statement

printf ("From Russia with love\n");


Method 3 is a combination of methods 1 and 2. For example, the preceding statement is equivalent to

printf("From " "Russia \
with " "love.\n");

How do we move the cursor to the beginning of the current line?

The escape sequence \r in the printf() format string

printf("I earned $50 \r Where is the money?\n");

will not display any character before \r. The escape sequence \r represents a carriage return and moves the cursor to the beginning of the current line.

Can I use the linefeed symbol by itself?

Yes, the symbol \n can be used by itself to advance a line as long as it is contained in double quotes. For example

printf("\n");

How do we linefeed a line?

The linefeed operation can be done easily with the printf() function using the linefeed symbol \n consists of two characters, \ (backslash, not to be confused with slash, /) and n, with no blank in between. In C, the two character symbol \n is one of many character escape sequences. The C compiler considers an escape sequence within a string literal as one character (not two). The importance of this will be seen later. The escape sequence \n causes the cursor to move to the next line and will not be displayed on the screen. Any data behind this symbol is written at the beginning of the next line. You can use \n at any location in the string literal. The \n can be at the beginning, in the middle, or at the end of a string. The number of \n can be more than one. For example, in the statement:

printf("\nHow do we\njump\n\ntwo lines? \n");

the program uses the first \n to move the cursor to a newline, displays "How do we" uses the second \n to jump to a new line, prints "jump" uses the next two \n to jump another two lines, prints "two lines?" and uses the last \n to jump one more line.

How do we write valuable comments?

Be wise in your use of comments. Remember that comments are used to enhance the understandability of your programs. Make them pleasing to the eye and clear. With practice, you will develop a style of writing comments that is of benefit to you. I do not use many comments, primarily because I want you to interpret the code yourself. Your programs should use comments far more frequently than I use them.
I recommend that you avoid writing comments on the same line as other C code unless you can clearly distinguish the comments from the code. It often looks much better if your comments are on lines separate from other statements. There is no standard for writing comments, but I like a style that highlights comments and separates them from other C text. The reason for this is that, if not highlighted, comments tend to blend in with the rest of the code and make following the logic of the code confusing. In other words, do not hide your comments. Make them stand out- they are there to help you and others. I like a style in which each comment line begins with two stars, and the comment block begins and ends with a line of stars. For instance, I strongly recommend that you add a banner at the beginning of your programs. A banner is a set of comments that describe such things as the name, parameters used, history, author, purpose, and date of the program. A better look would be as follows:

/*********************************************************************
** Name: Hola.C
** Purpose: Learning how to write comments in C
** Date: Written on 1/4/12
** Author: 3nriched
** Reference: None
*********************************************************************/

#include

int main(void)
{
printf("How do we write comments in C?");
}


Can we write a nested comment?

No, comment statements cannot be nested (meaning that we cannot write a comment within a comment) in C. For example:

/*/* This is an illegal comment because it is */ nested */

Can a comment appear in a C statement?

That depends. The C compiler treats comments like a single white space character. Therefore, comments can appear in a C statement only where a white space character is allowed. This means that comments may be placed between tokens but not within a token. (Note: a string literal is a token.)

Examples of correct comments:

printf /*This comment is legal */("Welcome to C!");
printf ( /*This comment is also legal*/"Welcome to C!");

Examples of incorrect comments:

pr /* This comment is illegal because it splits a C function
name (i.e., a token) */ intf("Welcome to C!");

printf("This is not a comment and /*will be displayed*/ ");

The text contained in the /* and */ is not a comment because it becomes part of the string literal and will be displayed. For this incorrect comment, the compiler will not indicate an error, it will simply print the phrase:

This is not a comment and /*will be displayed*/

on the screen. For the other comments, the compiler will indicate an error when you try to compile the program.

Can we write comments at the very beginning and end of a program?

Yes, a comment line can be written in the very first line of a program. It also can be written on the very last line of a program.

What is the structure of a comment?

The syntax of a C comment is:

/* Any text, number, or character */

where there should be no blanks(s) between the slash and the asterisk. In addition, the /* and */ must form a couple. The /* and */ are called comment delimiters.
The /* and */ must form a couple, but they need not be on the same line. Therefore, a comment line may occupy more than one line. A multi-line comment starts with /* followed by multiple lines of text consisting of numbers, characters, or symbols. The multi-line comment terminates with */.

Examples of incorrect comments:

/* Wrong comment 1, and no end asterisk and slash
/* Wrong comment 2, no end slash
/ *Wrong comment 3, there is a blank between / and * */

Why is the look of a program important?

The look of a program is important because programs continually undergoing change. A program that is neat and organized is easier to understand and therefore easier to modify. As a result, the likelihood for error is reduced in programs that follow a certain visual and organizational style compared to those that do not.

Is it necessary to use different lines in writing code?

A white-space character, such as that created when you press the Enter key, used between tokens is invisible to the C compiler. Therefore, you have the freedom to write C code at any row or column you like. The C compiler, for example, allows you to rewrite and pack into one line:

#include void main(void){printf("This is C!");}

or rewrite it as

#include

void main(void)
{
printf("This is C!");
}

However, these styles will make your program more difficult to understand and should not be used.

There is no required form for spacing within your programs. However, your instructor or employer may want you to adhere to certain standard accepted styles. Our example programs are meant to illustrate acceptable style, however, at times, publishing constraints do not allow us to follow any one accepted style rigorously. Indentation and spacing are considered important for the look of a program, even though they do not affect performance. To make your program readable, do such things as write one statement per line, line up your braces, and add blank lines where there are natural breaks in code instructions.

Where are blank spaces permitted in C code?

C code consists of a number of tokens. A C token is the smallest element that the C compiler does not break down into smaller parts. A token can be a function name, such as main, or a C reserved word. All C words should be written continuously. For example, the expression

void ma in(void)

is not legal because no blank characters are allowed between the characters a and i in the word main.

Between tokens, white-space characters (such as blank, tab, or the carriage return) can be inserted, but this is optional. For example, the line

void main(void)

is equivalent to

void main ( void )

or

void main ( void)

In general, it is acceptable to add blanks between tokens but not acceptable to add blanks within tokens.

Can I use both uppercase and lowercase letters to write C code?

The C language distinguishes between lower- and uppercase letters. Thus, printf is different from PRINTF, Printf, or PrIntF. It is said, therefore, that C is considered to be case sensitive. Both main and printf must be written in lowercase letters. For naming self-developed functions, you may use whatever case you consider appropriate. However, C traditionally is written primarily in lowercase letters. We describe situations when other than lowercase letters commonly are used, as the need arises.

Will the follow C program work correctly?

main()
{
printf("This is C!");
}


It may. However, this depends on your compiler. The reason it may work is that;

1) This file stdio.h is used so frequently in C that, for some compilers, it is attached automatically to programs despite no specific direction to do this.

2) Even though you have not written "void main(void)"-that is, the voids are missing-C assigns default types for the voids. The word default is used commonly in computing. A default value is a value that is used when none is specified. Without going into detail, because C assigns default types for missing voids, this program may work. However, I would not recommend that you write your programs in this manner.

What is the meaning of the braces?

After the line that contains the function name is the function body. The function body has the following features:

It begins with an opening brace {

It ends with a closing brace }

The pair of braces, {}. are used to enclose what is called a block of code. We use braces quite frequently to form blocks of code. Sometimes we use blocks within blocks, In this case, the braces enclose the block of code that is the function body.

The function body consists of C declaration(s) and statement(s). The structure of a typical C main function is as follows:

void main(void)
{
declaration 1;
declaration 2;
statement 1;
statement 2;
}

Why does it need to be called main?

The C compiler needs to know where execution is to begin. By definition, the primary function, main, is the first function to be executed. Other functions can be named almost anything that you want. A typical program has a large number of functions that you have written. The C compiler searches for the function named main and compiles the program in a manner to ensure that main is the first function executed.