Monday, May 31, 2010

Predefined Macros

Every compiler that conforms to the ISO C standard must define the following seven macros. Each of these macro names begins and ends with two underscore characters:

_ _DATE_ _

The replacement text is a string literal containing the compilation date in the format "Mmm dd yyyy" (example: "Mar 19 2006"). If the day of the month is less than 10, the tens place contains an additional space character.

_ _FILE_ _

A string literal containing the name of the current source file.

_ _LINE_ _

An integer constant whose value is the number of the line in the current source file that contains the _ _LINE_ _ macro reference, counting from the beginning of the file.

_ _TIME_ _

A string literal that contains the time of compilation, in the format "hh:mm:ss" (example: "08:00:59").

_ _STDC_ _

The integer constant 1, indicating that the compiler conforms to the ISO C standard.

_ _STDC_HOSTED_ _

The integer constant 1 if the current implementation is a hosted implementation; otherwise the constant 0.

_ _STDC_VERSION_ _

The long integer constant 199901L if the compiler supports the C99 standard of January 1999.

The values of the _ _FILE_ _ and _ _LINE_ _ macros can be influenced by the #line directive. The values of all the other predefined macros remains constant throughout the compilation process.

The value of the constant _ _STDC_VERSION_ _ will be adjusted with each future revision of the international C standard.

Under the C99 standard, C programs are executed either in a hosted or in a freestanding environment. Most C programs are executed in a hosted environment, which means that the C program runs under the control and with the support of an operating system. In this case, the constant _ _STDC_HOSTED_ _ has the value 1, and the full standard library is available.

A program in a freestanding environment runs without the support of an operating system, and therefore only minimal standard library resources are available to it.

Unlike the macros listed previously, the following standard macros are optional. If any of these macros is defined, it indicates that the implementation supports a certain IEC or ISO standard:

_ _STDC_IEC_559_ _

This constant is defined with the value 1 if the implementation's real floating-point arithmetic conforms to the IEC 60559 standard.

_ _STDC_IEC_559_COMPLEX_ _

This constant is defined with the value 1 if the implementation's complex floating-point arithmetic also conforms to the IEC 60559 standard.

_ _STDC_ISO_10646_ _

This long integer constant represents a date in the form yyyymmL (example: 199712L). This constant is defined if the encoding of wide characters with type wchar_t conforms to the ISO/IEC 10646 standard, including all supplements and corrections up to the year and month indicated by the macro's value.

You must not use any of the predefined macro names described in this section in a #define or #undef directive. Finally, the macro name _ _cplusplus is reserved for C++ compilers, and must not be defined when you compile a C source file.

Source: C in a Nutshell - O'Reilly Media

The _Pragma Operator

You cannot construct a #pragma directive (or any other preprocessor directive) by means of a macro expansion. For cases where you would want to do that, C99 has also introduced the preprocessor operator _Pragma, which you can use with macros. Its syntax is as follows:

_Pragma ( string_literal )

Here is how the _Pragma operator works. First, the string_literal operand is "de-stringized," or converted into a sequence of preprocessor tokens, in this way: the quotation marks enclosing the string are removed; each sequence of a backslash followed by a double quotation mark (\") is replaced by a quotation mark alone ("); and each sequence of two backslash characters (\\) is replaced with a single backslash (\). Then the preprocessor interprets the resulting sequence of tokens as if it were the text of a #pragma directive.

The following line defines a helper macro, STR, which you can use to rewrite any #pragma directive using the _Pragma operator:

#define STR(s) #s // This # is the "stringify" operator.

With this definition, the following two lines are equivalent:

#pragma tokens

_Pragma ( STR(tokens) )

The following example uses the _Pragma operator in a macro:

#define ALIGNMENT(n) _Pragma( STR(pack(n)) )

ALIGNMENT(2)

Macro replacement changes the ALIGNMENT(2) macro call to the following:

_Pragma( "pack(2)" )

The preprocessor then processes the line as it would the following directive:

#pragma pack(2)

Source: C in a Nutshell - O'Reilly Media

The #pragma Directive

The #pragma directive is a standard way to provide additional information to the compiler. This directive has the following form:

#pragma [tokens]

If the first token after #pragma is STDC, then the directive is a standard pragma. If not, then the effect of the #pragma directive is implementation-dependent. For the sake of portability, you should use #pragma directives sparingly.

If the preprocessor recognizes the specified tokens, it performs whatever action they stand for, or passes information on to the compiler. If the preprocessor doesn't recognize the tokens, it must ignore the #pragma directive.

Recent versions of the GNU C compiler and Microsoft's Visual C compiler both recognize the pragma pack(n), for example, which instructs the compiler to align structure members on certain byte boundaries. The following example uses pack(1) to specify that each structure member be aligned on a byte boundary:

#if defined( _ _GNUC_ _ ) || defined( _MSC_VER )

#pragma pack(1) // Byte-aligned: no padding.

#endif

Single-byte alignment ensures that there are no gaps between the members of a structure. The argument n in a pack pragma is usually a small power of two. For example, pack(2) aligns structure members on even-numbered byte addresses, and pack(4) on four-byte boundaries. pack( ) with no arguments resets the alignment to the implementation's default value.

C99 introduced the following three standard pragmas:

#pragma STDC FP_CONTRACT on_off_switch

#pragma STDC FENV_ACCESS on_off_switch

#pragma STDC CX_LIMITED_RANGE on_off_switch

The value of the on_off_switch must be ON, OFF, or DEFAULT.

Source: C in a Nutshell - O'Reilly Media

Generating Error Messages

The #error directive makes the preprocessor issue an error message, regardless of any actual formal error. Its syntax is:

#error [text]

If the optional text is present, it is included in the preprocessor's error message. The compiler then stops processing the source file and exits as it would on encountering a fatal error. The text can be any sequence of preprocessor tokens. Any macros contained in it are not expanded. It is a good idea to use a string literal here to avoid problems with punctuation characters, such as single quotation marks.

The following example tests whether the standard macro _ _STDC_ _ is defined, and generates an error message if it is not:

#ifndef _ _STDC_ _

#error "This compiler does not conform to the ANSI C standard."

#endif

Defining Line Numbers

The compiler includes line numbers and source filenames in warnings, error messages, and information provided to debugging tools. You can use the #line directive in the source file itself to change the compiler's filename and line numbering information. The #line directive has the following syntax:

#line line_number ["filename"]

The next line after a #line directive has the number specified by line_number. If the directive also includes the optional string literal "filename", then the compiler uses the contents of that string as the name of the current source file.

The line_number must be a decimal constant greater than zero. An example:

#line 1200 "primary.c"

The line containing the #line directive may also contain macros. If so, the preprocessor expands them before executing the #line directive. The #line directive must then be formally correct after macro expansion.

Programs can access the current line number and filename settings as values of the standard predefined macros _ _LINE_ _ and _ _FILE_ _:

printf( "This message was printed by line %d in the file %s.\n", _ _LINE_ _, _ _FILE_ _ );

The #line directive is typically used by programs that generate C source code as their output. By placing the corresponding input file line numbers in #line directives, such programs can make the C compiler's error messages refer to the pertinent lines in the original source.


Source: C in a Nutshell - O'Reilly Media

The token-pasting operator

The operator ## is a binary operator, and can appear in the replacement text of any macro. It joins its left and right operands together into a single token, and for this reason is commonly called the token-pasting operator. If the resulting text also contains a macro name, the preprocessor performs macro replacement on it. Whitespace characters that occur before and after the ## operator are removed along with the operator itself.

Usually, at least one of the operands is a macro parameter. In this case, the argument value is first substituted for the parameter, but the macro expansion itself is postponed until after token-pasting. An example:

    #define TEXT_A "Hello, world!"     #define msg(x) puts( TEXT_ ## x )     msg(A);

Regardless of whether the identifier A has been defined as a macro name, the preprocessor first substitutes the argument A for the parameter x, and then performs the token-pasting operation. The result of these two steps is the following line:

    puts( TEXT_A );

Now, because TEXT_A is a macro name, the subsequent macro replacement yields this statement:

    puts( "Hello, world!" );

If a macro parameter is an operand of the ## operator and a given macro invocation contains no argument for that parameter, then the preprocessor uses a placeholder to represent the empty string substituted for the parameter. The result of token pasting between such a placeholder and any token is that token. Token-pasting between two placeholders results in one placeholder. When all the token-pasting operations have been carried out, the preprocessor removes any remaining placeholders. Here is an example of a macro call with an empty argument:

    msg( );

This call expands to the following line:

    puts( TEXT_ );

If TEXT_ is not an identifier representing a string, the compiler will issue an error message.

The order of evaluation of the stringify and token-pasting operators # and ## is not specified. If the order matters, you can influence it by breaking a macro up into several macros.


Source: C in a Nutshell - O'Reilly Media

The stringify operator

The unary operator # is commonly called the stringify operator (or sometimes the stringizing operator) because it converts a macro argument into a string. The operand of # must be a parameter in a macro replacement text. When a parameter name appears in the replacement text with a prefixed # character, the preprocessor places the corresponding argument in double quotation marks, forming a string literal. All characters in the argument value itself remain unchanged, with the following exceptions:
  • Any sequence of whitespace characters between tokens in the argument value is replaced with a single space character.

  • A backslash character (\) is prefixed to each double quotation mark character (") in the argument.

  • A backslash character is also prefixed to each existing backslash that occurs in a character constant or string literal in the argument, unless the existing backslash character introduces a universal character name.

The following example illustrates how you might use the # operator to make a single macro argument work both as a string and as an arithmetic expression in the replacement text:

    #define printDBL( exp ) printf( #exp " = %f ", exp )     printDBL( 4 * atan(1.0));       // atan( ) is declared in math.h.

The macro call in the last line expands to this statement:

    printf( "4 * atan(1.0)" " = %f ", 4 * atan(1.0));

Because the compiler merges adjacent string literals, this code is equivalent to the following:

    printf( "4 * atan(1.0) = %f ", 4 * atan(1.0));

That statement would generate the following console output:

    4 * atan(1.0) = 3.141593

Source: C in a Nutshell - O'Reilly Media

How the Preprocessor Finds Header Files

It is up to the given C implementation to define where the preprocessor searches for files specified in #include directives. Whether filenames are case-sensitive is also implementation-dependent. For files specified between angle brackets, the preprocessor usually searches in certain system directories, such as /usr/local/include and /usr/include on Unix systems, for example.

For files specified in quotation marks ("filename"), the preprocessor usually looks in the current directory first, which is typically the directory containing the program's other source files. If such a file is not found in the current directory, the preprocessor searches the system include directories as well. A filename may contain a directory path. If so, the preprocessor looks for the file only in the specified directory.

You can always specify your own search path for #include directives, either by using an appropriate command-line option in running the compiler, or by adding search paths to the contents of an environment variable, often named INCLUDE. Consult your compiler's documentation.

Source: C in a Nutshell - O'Reilly Media

Monday, May 24, 2010

Null Pointers

A null pointer constant is an integer constant expression with the value 0, or such an expression cast as the type void *. The macro NULL is defined in stdlib.h, stdio.h and other header files as a null pointer constant.

#include /* ... */
FILE *fp = fopen( "demo.txt", "r" );
if ( fp == NULL )
{   // Error: unable to open the file demo.txt for reading.
}

Null pointers are implicitly converted to other pointer types as necessary for assignment operations, or for comparisons using == or !=. Hence no cast operator is necessary in the previous example. A null pointer is what results when you convert a null pointer constant to a pointer type.

Source: C in a Nutshell - O'Reilly Media

void Pointers

A pointer to void, or void pointer for short, is a pointer with the type void *. As there are no objects with the type void, the type void * is used as the all-purpose pointer type. In other words, a void pointer can represent the address of any object but not its type. To access an object in memory, you must always convert a void pointer into an appropriate object pointer.

To declare a function that can be called with different types of pointer arguments, you can declare the appropriate parameters as pointers to void. When you call such a function, the compiler implicitly converts an object pointer argument into a void pointer. A common example is the standard function memset( ), which is declared in the header file string.h with the following prototype:

void *memset( void *s, int c, size_t n );

The function memset( ) assigns the value of c to each of the n bytes of memory in the block beginning at the address s. For example, the following function call assigns the value 0 to each byte in the structure variable record:

struct Data { /* ... */ } record;
memset( &record, 0, sizeof(record) ); 

The argument &record has the type struct Data *. In the function call, the argument is converted to the parameter's type, void *.

The compiler likewise converts void pointers into object pointers where necessary. For example, in the following statement, the malloc( ) function returns a void pointer whose value is the address of the allocated memory block. The assignment operation converts the void pointer into a pointer to int:

int *iPtr = malloc( 1000 * sizeof(int) ); 

Source: C in a Nutshell - O'Reilly Media

Optimization in programming

Optimization is the art of going through a program and making the code more efficient so that it runs faster. Most compilers have a command-line switch that causes them to generate optimized code. This efficiency comes at the cost of compile time; the compiler takes a lot longer to generate code when optimization is turned on.
The other type of optimization occurs when a programmer modifies a program to use a more efficient algorithm. This section discusses this second type of optimization.

How to Optimize:
Here are several optimizing strategies mentioned:
Loop ordering:
Nested loops should be ordered with the simplest loop outermost and the
most complex loops innermost.

Reduction in strength:
This phrase is a fancy way of saying you should use cheap operations instead
of expensive ones. The table at the top-right hand side explains the relative cost of each operation in a descending order.
Powers of 2:
Use a power of 2 when doing integer multiply or divide. Most compilers
substitute a shift for the operation.
Pointers:
Using pointers is faster than indexing an array. Pointers are, however, more
tricky to use.
Macros:
Using a macro eliminates the overhead associated with a function call. It also
makes the code bigger and a little more difficult to debug.



Saturday, May 22, 2010

#define vs. const

The const keyword is relatively new. Before const, #define was the only keyword available to define constants, so most older code uses #define directives. However,the useof const is preferred over #define for several reasons. First of all, C checks the syntax of const statements immediately. The #define directive is not checked until the macro is used. Also const use s C syntax, while the #define has a syntax all its own. Finally, const follows normal C scope rules, while constantsdefined by a #define directive continue on forever.

So, in most cases, a const statement is preferred over #define . Here are two ways of defining the same constant:

#define MAX 10 /* Define a value using the preprocessor */
/* (This definition can easily cause problems) */
const int MAX = 10; /* Define a C constant integer */
/* (safer) */

The #define directive can only define simple constants. The const statement can define almost any type of C constant, including things like structure classes. For example:
struct box {
int width, height; /* Dimensions of the box in pixels */
};
const box pink_box ={1.0, 4.5};/* Size of a pink box to be used for input */

The #define directive is, however, essential for things like conditional compilation
and other specialized uses.

Some compilers will not allow you to use a constant to define the size of an array. They should, but they have not caught up to the standard yet.

Software life cycle


The major steps in making a program are:

· Requirements. Programs start when someone gets an idea and starts to implement it. The requirement document describes, in very general terms, what is wanted.

· Program specification. The specification is a description of what theprogram does. In the beginning, a preliminary specification is used to describe what the program is going to do. Later, as the program becomes more refined, so does the specification. Finally, when the program is finished, the specification serves as a complete description of what the program does.

· Code design. The programmer does an overall design of the program. The design should include major algorithms, module definitions, file formats, and data structures.

· Coding. The next step is writing the program. This step involves first writing a prototype and then filling it in to create the full program.

· Testing. The programmer should design a test plan and then use it to test his program. When possible, the programmer should have someone else test the program.

· Debugging. Unfortunately, very few programs work the first time. They must be corrected and tested again.

· Release. The program is packaged, documented, and sent out into the world to be used.

· Maintenance. Programs are never perfect. Bugs will be found and will need correction. This step is the maintenance phase of programming.

· Revision and updating. After a program has been working for a while, the users will want changes, such as more features or more intelligent algorithms. At this point, a new specification is created and the process starts again.

Source: Practical C Programming, Third Edition -O'Reilly Media

Initializing Variables in C

C allows variables to be initialized in the declaration statement. For example, the

following statement declares the integer counter and initializes it to 0:

int counter = 0; /* number cases counted so far */

Arrays can also be initialized in this manner. The element list must be enclosed in

curly braces ({}). For example:

/* Product numbers for the parts we are making */

int product_codes[3] = {10, 972, 45};

The previous initialization is equivalent to:

product_codes[0] = 10;

product_codes[1] = 972;

product_codes[2] = 45;

The number of elements in {} does not have to match the array size. If too many

numbers are present, a warning will be issued. If an insufficient amount of numbers

are present, C will initialize the extra elements to 0.

If no dimension is given, C will determine the dimension from the number of

elements in the initialization list. For example, we could have initialized our variable

product_codes with the state ment:

/* Product numbers for the parts we are making */

int product_codes[] = {10, 972, 45};

Initializing multidimensional arrays is similar to initializing single-dimension arrays.

A set of brackets ([ ]) encloses each dimension. The declaration:

int matrix[2][4]; /* a typical matrix */

can be thought of as a declaration of an array of dimension 2 with elements that are

arrays of dimension 4. This array is initialized as follows:

/* a typical matrix */

int matrix[2][4] =

{

{1, 2, 3, 4},

{10, 20, 30, 40}

};

Strings can be initialized in a similar manner. For example, to initialize the variable

name to the string "Sam", we use the statement:

char name[] = {'S', 'a', 'm', '\0'};

C has a special shorthand for initializing strings: Surround the string with double

quotes ("") to simplify initialization. The previous example could have been written:

char name[] = "Sam";

The dimension of name is 4, because C allocates a place for the '\0' character that

ends the string.

The following declaration:

char string[50] = "Sam";

is equivalent to:

char string[50];

.

.

.

strcpy(string,"Sam");

An array of 50 characters is allocated but the length of the string is 3.

Source: Practical C Programming, Third Edition - O'Reilly Media

String and Character Constants

String and character constants are very different. Strings are surrounded by double quotes (") and
characters by single quotes ('). So "X" is a one-character string, while 'Y' is just a single character.

The string "X" takes up two bytes, one for the X and one for the end-of-string (\0). The character 'Y' takes up one byte.

Indentation and Code Format

In 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.
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. Programmer should use the format which he/she feels 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.

Source:

Tuesday, May 11, 2010

Floating Point Versus Integer Divide

Look at the program:
int main() {
float ans;
ans=5/10;
printf("%f",ans);
return 0;
}

what is the output?
The output is not like this: 0.50000

The output is 0.000000
because int/int = int

so change the program to
int main(void) {
float ans;
ans=5/10.0;
printf("%f",ans);
return 0;
}

the above program is (int/float)
so the output is now 0.500000

NOTE:
int/int = int
int/float = float
float/int = float
float/float = float

The above table can be summarized as: integer division takes place only when both elements are integers.

The below mentioned information is from: Practical C Programming, Third Edition - O'Reilly Media

The division operator is special. There is a vast difference between an integer divide
and a floating-point divide. In an integer divide, the result is truncated (any
fractional part is discarded). So the value of 19/10 is 1.

If either the divisor or the dividend is a floating-point number, a floating-point divide
is executed. So 19.0/10.0 is 1.9. (19/10.0 and 19.0/10 are also floating-point
divides; however, 19.0/10.0 is preferred for clarity.)


List of Hello World Programs in 300 Programming Languages

List of Hello World Programs in 300 Programming Languages

Conversion between number and string

Random Number between two integers in C

Finding out a RANDOM NUMBER bettween two integers a & b in C Language:

We are aware of the rand() function:

rand() calculates and returns the pseudo-random integer in the range 0 to RAND_MAX
where RAND_MAX is a constant defined in . Its default value may vary between implementations but it is granted to be at least 32767.

Step by Step Solution:
result = rand() % b;// result lies in between 0 and (b-1)
result = ((rand() % b) + a);// result lies in between a and (a+(b-1))
result = ((rand() % ((b+1)-a)) + a);// result lies in between a and b

From the third solution the minimum value of the random number will be (0+a) = a, and maximum value of the random number will be (b-a+a) = b.