Archive for the ‘C brainstorming’ Category

Reference vs. Pointer

April 29, 2009

Reference Pointer
1>is an object which IS AN ALIAS for another object.] [is an object that CONTAINS THE ADRRESS IN MEMORY of another object]

2>the preferred way of undirectly access objects.] [you should use it just if you really need it, as it it lets you to work in a lower level than a reference does]

3>keeps your code clear .] the code is less clear but still understandable

4>it must be initialized when created . you don’t have to initialize it when declared

5>it references to the one object and only
that one, therefore you can not modify
the address referenced.]
because it contains an address, it can point to many different objects during lifetime. The address can be manipulated

6>when used, the address is dereferenced without using any particular operator] the address must be dereferenced using the * operator

abt storage class n type qualifier

September 2, 2007

This is a part of a variable declaration that tells the compiler how to interpret the variable’s symbol. It does not in itself allocate storage, but it usually tells the compiler how the variable should be stored. Storage class specifiers help you to specify the type of storage used for data objects. Only one storage class specifier is permitted in a declaration this makes sense, as there is only one way of storing things and if you omit the storage class specifier in a declaration, a default is chosen. The default depends on whether the declaration is made outside a function (external declarations) or inside a function (internal declarations). For external declarations the default storage class specifier will be extern and for internal declarations it will be auto. The only exception to this rule is the declaration of functions, whose default storage class specifier is always extern.

Here are C’s storage classes and what they signify:

* auto – local variables.
* static – variables are defined in a nonvolatile region of memory such that they retain their contents though out the program’s execution.
* register – asks the compiler to devote a processor register to this variable in order to speed the program’s execution. The compiler may not comply and the variable looses it contents and identity when the function it which it is defined terminates.
* extern – tells the compiler that the variable is defined in another module.

In C, const and volatile are type qualifiers. The const and volatile type qualifiers are completely independent. A common misconception is to imagine that somehow const is the opposite of volatile and vice versa. This is wrong. The keywords const and volatile can be applied to any declaration, including those of structures, unions, enumerated types or typedef names. Applying them to a declaration is called qualifying the declaration?that’s why const and volatile are called type qualifiers, rather than type specifiers.

* const means that something is not modifiable, so a data object that is declared with const as a part of its type specification must not be assigned to in any way during the run of a program. The main intention of introducing const objects was to allow them to be put into read-only store, and to permit compilers to do extra consistency checking in a program. Unless you defeat the intent by doing naughty things with pointers, a compiler is able to check that const objects are not modified explicitly by the user. It is very likely that the definition of the object will contain an initializer (otherwise, since you can’t assign to it, how would it ever get a value?), but this is not always the case. For example, if you were accessing a hardware port at a fixed memory address and promised only to read from it, then it would be declared to be const but not initialized.
* volatile tells the compiler that other programs will be modifying this variable in addition to the program being compiled.

For example, an I/O device might need write directly into a program or data space. Meanwhile, the program itself may never directly access the memory area in question.

In such a case, we would not want the compiler to optimize-out this data area that never seems to be used by the program, yet must exist for the program to function correctly in a larger context.

It tells the compiler that the object is subject to sudden change for reasons which cannot be predicted from a study of the program itself, and forces every reference to such an object to be a genuine reference.
* const volatile – Both constant and volatile.
The “volatile” modifier

The volatile modifier is a directive to the compiler?s optimizer that operations involving this variable should not be optimized in certain ways.

There are two special cases in which use of the volatile modifier is desirable.

The first case involves memory-mapped hardware (a device such as a graphics adaptor that appears to the computer?s hardware as if it were part of the computer?s memory),

and the second involves shared memory (memory used by two or more programs running simultaneously).

Most computers have a set of registers that can be accessed faster than the computer?s main memory.

A good compiler will perform a kind of optimization called ?redundant load and store removal.?

The compiler looks for places in the code where it can either remove an instruction to load data from memory because the value is already in a register, or remove an instruction to store data to memory because the value can stay in a register until it is changed again anyway.
If a variable is a pointer to something other than normal memory, such as memory-mapped ports on a peripheral, redundant load and store optimizations might be detrimental. For instance, here?s a piece of code that might be used to time some operation:

time_t time_addition(volatile const struct timer *t, int a)
int n;
int x;
time_t then;
x = 0;
then = t->value;
for (n = 0; n < 1000; n++)
x = x + a;
return t->value – then;

In this code, the variable t->value is actually a hardware counter that is being incremented as time passes. The function adds the value of a to x 1000 times, and it returns the amount the timer was incremented by while the 1000 additions were being performed. Without the volatile modifier, a clever optimizer might assume that the value of t does not change during the execution of the function, because there is no statement that explicitly changes it. In that case, there?s no need to read it from memory a second time and subtract it, because the answer will always be 0. The compiler might therefore ?optimize? the function by making it always return 0. If a variable points to data in shared memory, you also don?t want the compiler to perform redundant load and store optimizations. Shared memory is normally used to enable two programs to communicate with each other by having one program store data in the shared portion of memory and the other program read the same portion of memory. If the compiler optimizes away a load or store of shared memory, communication between the two programs will be affected.

What is the difference between constants defined through #define and the constant keyword?

September 2, 2007

A constant is similar to a variable in the sense that it represents a memory location (or simply, a value). It is different from a normal variable, in that it cannot change it’s value in the proram – it must stay for ever stay constant.

So whats the difference between these two?

#define ABC 5


const int abc = 5;

There are two main advantages of the second one over the first technique. First, the type of the constant is defined. “pi” is float. This allows for some type checking by the compiler.

Second, these constants are variables with a definite scope. The scope of a variable relates to parts of your program in which it is defined.

There is also one good use of the important use of the const keyword. Suppose you want to make use of some structure data in some function. You will pass a pointer to that structure as argument to that function. But to make sure that your structure is readonly inside the function you can declare the structure argument as const in function prototype. This will prevent any accidental modification of the structure values inside the function.

How are floating point numbers stored? Whats the IEEE format?

September 2, 2007

IEEE Standard 754 floating point is the most common representation today for real numbers on computers, including Intel-based PC’s, mackintoshes, and most Unix platforms.

IEEE floating point numbers have three basic components: the sign, the exponent, and the mantissa. The mantissa is composed of the fraction and an implicit leading digit (explained below). The exponent base(2) is implicit and need not be stored.

The following figure shows the layout for single (32-bit) and double (64-bit) precision floating-point values. The number of bits for each field are shown (bit ranges are in square brackets):

Sign   Exponent   Fraction   Bias
Single Precision 1 [31] 8 [30-23]  23 [22-00] 127
Double Precision 1 [63] 11 [62-52] 52 [51-00] 1023

The sign bit is as simple as it gets. 0 denotes a positive number; 1 denotes a negative number. Flipping the value of this bit flips the sign of the number.

The exponent field needs to represent both positive and negative exponents. To do this, a bias is added to the actual exponent in order to get the stored exponent. For IEEE single-precision floats, this value is 127. Thus, an exponent of zero means that 127 is stored in the exponent field. A stored value of 200 indicates an exponent of (200-127), or 73.

For reasons discussed later, exponents of -127 (all 0s) and +128 (all 1s) are reserved for special numbers. For double precision, the exponent field is 11 bits, and has a bias of 1023.

The mantissa, also known as the significand, represents the precision bits of the number. It is composed of an implicit leading bit and the fraction bits. To find out the value of the implicit leading bit, consider that any number can be expressed in scientific notation in many different ways. For example, the number five can be represented as any of these:

5.00 � 1.00
0.05 � 10 ^ 2
5000 � 10 ^ -3

In order to maximize the quantity of representable numbers, floating-point numbers are typically stored in normalized form. This basically puts the radix point after the first non-zero digit. In normalized form, five is represented as 5.0 � 1.00. A nice little optimization is available to us in base two, since the only possible non-zero digit is 1. Thus, we can just assume a leading digit of 1, and don’t need to represent it explicitly. As a result, the mantissa has effectively 24 bits of resolution, by way of 23 fraction bits.

So, to sum up:

1. The sign bit is 0 for positive, 1 for negative.
2. The exponent’s base is two.
3. The exponent field contains 127 plus the true exponent for single-precision,
or 1023 plus the true exponent for double precision.
4. The first bit of the mantissa is typically assumed to be 1.f, where f is the
field of fraction bits.

What is the token pasting operator and stringizing operator in C?

September 1, 2007

Token pasting operator

ANSI has introduced a well-defined token-pasting operator, ##, which can be used like this:

#define f(g,g2) g##g2



  int var12=100;





Stringizing operator

#define sum(xy) printf(#xy " = %f\n",xy);



    sum(a+b); // As good as printf("a+b = %f\n", a+b);


So what does the message “warning: macro replacement within a string literal” mean?

#define TRACE(var, fmt) printf("TRACE: var = fmt\n", var)

TRACE(i, %d);

gets expanded as

printf("TRACE: i = %d\n", i);

In other words, macro parameters were expanded even inside string literals and character constants. Macro expansion is *not* defined in this way by K&R or by Standard C. When you do want to turn macro arguments into
strings, you can use the new # preprocessing operator, along with string literal concatenation:

#define TRACE(var, fmt) printf("TRACE: " #var " = " #fmt "\n", var)

See and try to understand this special application of the strigizing operator!

#define Str(x) #x
#define Xstr(x) Str(x)
#define OP plus

char *opname = Xstr(OP); //This code sets opname to “plus” rather than “OP”.

Here are some more examples


Define a macro DEBUG such that the following program

int main()
int x=4;
float a = 3.14;
char ch = 'A';

DEBUG(x, %d);
DEBUG(a, %f);
DEBUG(ch, %c);


DEBUG: x=4
DEBUG: y=3.140000

The macro would be

#define DEBUG(var, fmt) printf("DEBUG:" #var "=" #fmt "\n", var);


Write a macro PRINT for the following program

int main()
int x=4, y=4, z=5;
int a=1, b=2, c=3;

such that it outputs

x=4 y=4 z=5
a=1 b=2 c=3

Here is a macro that will do this

#define PRINT(v1,v2,v3) printf("\n" #v1 "=%d" #v2 "=%d" #v3 "=%d", v1, v2, v3)

How can I write a macro which takes a variable number of arguments?

September 1, 2007

One can define the macro with a single, parenthesized “argument” which in the macro expansion becomes the entire argument list, parentheses and all, for a function such as printf():

#define DEBUG(args) (printf("DEBUG: "), printf args)

if(n != 0) DEBUG(("n is %d\n", n));

The caller must always remember to use the extra parentheses.

Other possible solutions are to use different macros depending on the number of arguments.

C9X will introduce formal support for function-like macros with variable-length argument lists.

The notation … will appear at the end of the macro “prototype” (just as it does for varargs functions).

Is it acceptable to declare/define a variable in a C header?

September 1, 2007

A global variable that must be accessed from more than one file can and should be declared in a header file. In addition, such a variable must be defined in one source file.

Variables should not be defined in header files, because the header file can be included in multiple source files, which would cause multiple definitions of the variable.

The ANSI C standard will allow multiple external definitions, provided that there is only one initialization.

But because there?s really no advantage to using this feature, it?s probably best to avoid it and maintain a higher level of portability.

“Global” variables that do not have to be accessed from more than one file should be declared static and should not appear in a header file.

abt Lvalue n Rvalue

August 30, 2007

An lvalue can be defined as:“An address in the memory that is the location of an object whose contents can be modified.”

On the other hand, an rvalue can be defined as:”A value that does not necessarily have any storage address. An lvalue can be converted to an rvalue, but _not_ the other way around.”

In the following example, observe the usage of j:

int k, j; /* line 1 */
j = 5; /* line 2*/
k = j; /* line 3*/

The compiler treats the variable j in two different ways: in the line 2, j is the address of the integer object; and in the line 3, it is the value of that object! Technically, j is an lvalue in the line 2; and, a rvalue in the line 3.


An lvalue is an expression that could appear on the left-hand sign of an assignment (An object that has a location). An rvalue is any expression that has a value (and that can appear on the right-hand sign of an assignment).

The lvalue refers to the left-hand side of an assignment expression. It must always evaluate to a memory location. The rvalue represents the right-hand side of an assignment expression; it may have any meaningful combination of variables and constants.

Is an array an expression to which we can assign a value?

An lvalue was defined as an expression to which a value can be assigned. The answer to this question is no, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes.

The following statement is therefore illegal:

int x[5], y[5];
x = y;

Additionally, you might want to copy the whole array all at once. You can do so using a library function such as the memcpy() function, which is shown here:

memcpy(x, y, sizeof(y));

It should be noted here that unlike arrays, structures can be treated as lvalues.
structure variable to another structure variable of the same type, such as this:
Thus, you can assign one

typedef struct t_name
char last_name[25];
char first_name[15];
char middle_init[2];
NAME my_name, your_name;
your_name = my_name;


what is object in c?

August 30, 2007

The basic unit of data of a running program is an object; and if the program were written in C, then the sizes of objects would vary according to their data types.

So, what is an object? An object can be defined as:

“An object is a contiguous block of memory forming a single logical data structure. Objects are the units of allocation, deallocation, etc., and has a well-defined set of operations.”

Note: We use the term `object’ in a sense introduced by K&R , Objects and Lvalues, which has no relation with Object Oriented Programming.

As per the definition, an object type has a well-defined set of operations that can be applied upon it.  For example, the C language does not allow bit-wise operation on floating types, multiplication on pointer types, and cast operation on lvalues, etc.

C lang construct n diff data types

August 30, 2007

The C programming language offers various data types to suit different purposes.  They can be broadly categorized as follows:

+ Integral types (char, short, int, long, long long, enum, _Bool) (long long and _Bool are new feature of C99)

+ Real floating types (float, double, long double)

+ Complex floating types (float _Complex, double _Complex, long double _Complex) (New feature of C99)

+ void is an empty set of values

+ Derived types (structure type, union type, array type, pointer type, function type)

+ Incomplete type (array of unknown size, a structure or union of unknown content)

Real and complex floating types are collectively know as floating types; integral and floating types are collectively called arithmetic types; arithmetic and pointer types are collectively called scalar types; arrays and structures are collectively called aggregate types.