What makes C compiler better than the other? Well, that’s a question often debated upon. As we all know c is a general purpose programming language which was developed to run on UNIX operating system and till date it is the most widely used programming language being used to develop programs. it uses a weak compiler as compared to other language compilers.
The C compiler provides low level access to computer memory and offers programming constructs that are very easy to convert to machine level language. C compilers use minimum run time and they are very fats compilers though prone to errors. A C program can easily be converted to another language program with a minimum of rewriting. C compiler allows structured programming and is very flexible. Its static system avoids many of the errors that can happen during run time.
- C allows the executable code to be stored within functions.
- C compiler terminates a statement with a semicolon.
- C is basically a procedure oriented language.
There are many C compilers available in the market today and most them run on all operating systems including both windows and UNIX. Some of these c compilers are available as freeware, some are available under proprietary license, and some have BSD license and some other have GPL license. Many of the c compilers are not available online.
The best about C compilers is that a majority of them support “integrated development environment” or IDE which makes them more easy to use. Some C compilers apart from having IDE supporting feature come with some third party features which extend the functionality of the language and make it work faster. They provide better editing options and strong macros with great compiler integration and run time.
Most of these compilers take only 300 MB of space on your hard disk drive. For windows some are available in the size of 170 MB and so the installation process is not time consuming and does not checks your patience.
C compiler lets you use parallelism. Any source code before execution, needs to be converted into machine level language i.e., in the language that is easily understood by the CPU processor. C compiler does this effectively and very fast as compared to other language compilers available today.
C having a fast compiler is mostly used to write game codes. Since other languages are largely optimized, C is used widely even today. C compiler provides abstraction to a great degree. Compiling depends a lot on the length and complexity of the code and on the speed of the CPU processor. But, the C compiler compiles the required code in as less time as possible. C compiler being a very large and complex tool is very powerful and useful. C can be thought of as a portable assembly language and scripting of many other languages is based on C language only.
Learning all the features of C is a great deal. Many C compilers support all ANSI C standards. C compilers are so small that they can be directly used from a rescue disk. C compilers can produce x86 and x86- 64 code very fast. Many C compilers today come with an optional memory feature and a bound checker.
Few compilers can simultaneously compile and run the programs using the “command line” option. Under this feature programs run like shell scripts. The C compilers are exceptionally faster and better than any other compiler available today in terms of speed of compilation. C language is free of what is called bombastic jargon and it is not much optimized. Most of the C compilers like TCC produce codes in a single pass and each statement is compiled very carefully.
Wednesday, October 12, 2011
What makes one C compiler better than the other?
Posted by
Sunflower
at
10/12/2011 10:54:00 PM
0
comments
Labels: C Language, Code, Compile, Compiler, Complexity, Execution Integrated, Features, Functionality, Functions, Languages, Object Oriented, Programming, Statements
![]() | Subscribe by Email |
|
Tuesday, October 11, 2011
What are the problems of a C compiler?
Every programming language has some advantages and disadvantages which are not present in the other languages. Some languages are capable of solving some problems better as compared to other languages. But the point is that most of the problems have similar needs, requirements and logic, so the point where languages differ from each other is the efficiency with which they solve the problem.
Some provide more efficient and fluent solutions while others don’t. As we all know C is a basic programming language which was developed to solve problems and develop programs relating to kernels of the operating systems, compilers and graphical user interfaces. C compiler though being fast is not so efficient. It provides many downsides for a large number of problems. Many of us think that C is the fastest language but this is not true.
C++ compiles most of the C programs at the same speed as C++ does. Some of the features of C language like virtual function calls result in over heads. C is not object oriented. This in turn makes it more inconvenient to implement some programs. It is not able to force object orientation everywhere. C makes some programs that require object oriented programming more error prone. C has got a weak typing system as compared to other programming languages. This leads to many programming errors after compilation of the program.
A bigger standard library C++ allows the full use of the C standard library. This is very important of course, as the C standard library is an invaluable resource when writing real world programs.
- C++ has a library called the Standard Template Library.
- This standard library contains a number of templates that can be used while developing programs almost of any kind.
- It also includes many common data structures which are very useful like data lists, maps, data sets, etc. the standard library routines and its data structures are tailored to the specific needs of the programmer.
- Though standard library is no gold knife, still it does gives a great help in many programs for solving general purpose related problems. Many tasks like implementing a linked list in C take a lot of time.
- Though the compilation is fast but, who has got that much time to write those lengthy codes. That time you will feel the need for a better compiler which provides a shorter and effective code for implementing lists and other sorts of data structures in array form.
Even though C language was standardized long back in 1998, but till date we don’t have any good compilers for this language. It’s a very complex language and so requires a heavy compiler like itself to compile it. Another problem related to C compiling is that being a big and complex language, many few people have its correct knowledge of usage. A lot depends on the programmer also. If you are typing in the wrong code you are sure to get bad results.
Today also most of the programs are written in C. a need is felt to convert them to another programming language for better compilation. But the conversion is no good solution. Conversion of a C language program code is often ended up in rewriting almost the entire content of the program.
Programs written in C will always have 2 major problems. Firstly their code will be unusually lengthy and time consuming. Secondly, the program execution will be slower even though the compilation time is very less. The C program codes require more time to read, write and understand. C compiler being ineffective can crash any time. There’s a lack of high level routines in C compiler.
Posted by
Sunflower
at
10/11/2011 07:36:00 PM
0
comments
Labels: C, C Language, Compile, Compiler, Data Structures, Efficiency, Functions, Interface, Kernel, Languages, Library, Object Oriented, Operating Systems, Problems, Programs, Speed
![]() | Subscribe by Email |
|
Monday, October 10, 2011
Some details about Multi dimensional arrays in C...
An array can be defined as the collection of variables of the same type that are referenced by a common name. Arrays are of two types namely one dimensional arrays and multi dimensional arrays. One dimensional array consists of finite homogenous elements whereas a multi dimensional array is composed of elements each of which is itself an array. Arrays refer to a named list of a finite number n of similar data elements. Each of the data elements can be referenced respectively by a set of consecutive numbers, usually 0, 1, 2, 3, 4,….., n. the simplest form of a multi dimensional array is the two dimensional array.
You can declare a two dimensional array as follows:
Type array name [ rows ] [ columns ];
Where type is the base data type of the array having name name, rows, the first index, refers to the number of rows in the array and columns, the second index refers to the number of columns in t5he array. For example:
Int sales [ 5 ] [ 10 ] ;
The general form of array initialization is shown below:
Type array name [ size N ] = { value list } ;
The value list is a comma separated list of array elements values. The element’s values in the value list must have the same data type as that of the base type of the array.
Int days [ 5 ] = { 1, 2, 3, 4, 5 } ;
Character arrays can also be initialized as shown below:
Char string [ 10 ] = { ‘c’ , ‘a’ , ‘t’ ‘\0’ } ;
Multi-dimensional arrays can also be initialized in the same way as simple dimensions one. For example:
Int abc [ 3 ] [ 2 ] = { 1, 1,
2, 2,
3, 3 } ;
This can be done it the other way also :
Int abc [ 3 ] [ 2 ] = { 1, 1, 2, 2, 3, 3 } ;
A multi dimensional array of strings can be initialized as shown below:
Type array name [ size N ] = { value list } ;
Here type declares the base type of the array, the array name specifies the name with which the array will be referenced and size defines how many elements the array will hold. The size must be an integer value or integer constant without any sign. The value list is a comma separated list of array’s elements values. The element values in the value list must have the same data type as that of the base type of the array.
Int days [ 5 ] = { 1, 2, 3, 4, 5 } ;
Character arrays can also be initialized as shown below:
Char string [ 10 ] = { ‘c’ , ‘a’ , ‘t’ , ‘s’ , ‘\0’ } ;
Multi dimensional arrays are also initialized in the same as the single dimensional one. For example:
Int cube [ 3 ] [ 2 ] = { 1, 1,
2, 2,
3, 3 } ;
This can be done in the other way also:
Int abc [ 3 ] [ 2 ] = { 1, 1, 2, 2, 3, 3 } ;
A multi dimensional array of strings can be initialized as shown below:
Char abc [ 3 ] [ 2 ] = { “Sunday” , “Monday” } ;
C allows you to skip the size of the array in an array initialization statement. This is called unsized array initialization. C allows arrays of more than 2 dimensions. The exact limit of dimensions is determined by the compiler we are using.
Posted by
Sunflower
at
10/10/2011 04:44:00 PM
0
comments
Labels: Array, Arrays, C, C Language, Characters, Columns, Constants, Data, Data types, Dimensions, Initialization, Integer, Languages, Multi dimensional arrays, Rows, Strings, Types, Values, Variables
![]() | Subscribe by Email |
|
Saturday, October 8, 2011
Some details about Strings and Arrays of Strings in C
Multiple character constants can be dealt with in 2 ways in C. if enclosed in single quotes, these are treated as character constants and if enclosed in double quotes, these are treated as string literals. A string literal is a sequence of characters surrounded by double quotes. Each string literal is automatically added with a terminating character ‘\0’. Thus, the string “abc” will actually be represented as follows:
“ abc \0” in the memory and its size is not 3 but 4 characters ( inclusive of terminator character ).
Arrays refer to a named list of a finite number n of similar data structure elements. Each of the data elements can be referenced respectively by a set of consecutive numbers, usually 0, 1, 2, 3, ……., n. if the name of an array of 10 elements is ARR, then its elements will be referred as shown below:
ARR [ 0 ], ARR [ 1 ], ARR [ 2 ], ARR [3], …… ARR [9]
Arrays can be one dimensional, two dimensional or multi dimensional. The functions gets() and puts () are string functions. The gets() function accepts a string of characters entered at the keyboard and places them in the string variable mentioned with it. for example :
Char name[ 21 ];
The above code declares a string namely name which can store 20 valid characters ( width 21 specifies one extra character ‘\0’ with which a string is always terminated ). The function gets() reads a string of maximum 20 characters and stores it in a memory address pointed to by name. As soon as the carriage return is pressed, a null terminator ‘\0’ is automatically placed at the end of the string. The function puts () writes a string on the screen and advances the cursor to the newline. Any subsequent output will appear on the next line of the current output by puts ().
Arrays are a way to group a number of items into a larger unit. Arrays can have data items of simple types like int or float, or even of user defined types like structures and objects. An array can be of strings also. Strings are multi dimensional arrays comprised of elements, each of which is itself an array.
A string is nothing but an array of characters only. In actual C does not have a string data type rather it implements string as single dimension character arrays. Character arrays are terminated by a null character ‘\0’. So, for this reason the character arrays or strings are declared one character larger than the largest string they can hold.
Individual strings of the string array can be accessed easily using the index. The end of a string is determined by checking for null character. The size of the first index ( rows ) determines the number of strings and the size of the second index ( columns ) determines maximum length of each string. By just specifying the first index, an individual string can be accessed. You can declare and handle an array of strings just like a two dimensional array. See an example below:
Char name [10] [20] ;
Here the first dimension declares how many strings will be there in the array and the second dimension declares what will be the maximum length of a string. Unlike C++, C has some different functions for adding or concatenating strings, checking string length and to see the similarity of two strings. The functions are namely strlen, strcmp, strcat, strrev etc and are included in header file string.h. Strings are used for holding long inputs.
Posted by
Sunflower
at
10/08/2011 08:05:00 PM
1 comments
Labels: Array of strings, C Language, Characters, Code, Constants, Data, Dimensions, Elements, Function, Inputs, Memory, Outputs, Strings, Structure, Types, Values, Variables
![]() | Subscribe by Email |
|
Thursday, October 6, 2011
Some details about Pointers in C...
There was a need for a kind of variable that could store the address of another variable, so that the value of he variable could be directly accessed through its memory address and could be manipulated more easily and in a short span of time. The “pointer” is such a variable invented. It can be defined as a variable which stores the address of another variable. A pointer can be declared easily as shown below:
int *ptr1;
The “int” keyword is used to tell compiler that the pointer “ptr1” will store the memory address of an integer type variable. The symbol “*” called asterisk is used to tell the compiler that the variable “ptr1” is actually a pointer and that it will store the address of the variable it is pointing to irrespective of the bytes it will require to store the memory address. The pointer “ptr1” is said to point to an integer variable. N the above declaration we didn’t provide ptr1 with a value i.e., it’s empty now. If the declaration is made outside the function, the pointer “ptr1” will be initialized to a value that will not point to any of the variables or objects in a C program. Pointers initialized in this manner are said to have a null value or are called as “null” pointers. Null pointers are very useful in many of the C programs as they prevent system crash. A null pointer is implemented using a macro. The macro used is called “NULL” macro. If you set the value of a pointer using the above mentioned macro through an assignment statement as shown below:
Ptr1 = NULL;
It is assured that the pointer is now having a null value or it has become a null pointer. A null pointer can be tested using the below given statement
if (ptr 1== NULL);
Now suppose we want to store the address of an integer a in the above declared pointer “ptr1”, we will use the following statement:
ptr1 = &a;
Before proceeding further, we should now that a pointer has two values attached to it. One is the “l value” and the other one is the “r value”. L value is where the address of the variable pointed to is stored. R value stores the value of that variable. Now, the function of the “&” operator is to retrieve this l value of the variable a. the assignment operator copies the address of the variable a to the pointer “ptr1”. Now the pointer “ptr1” is said to point to variable “a”.
The “*” operator is also called the dereferencing operator and is used for de-referencing as follows:
*ptr 1 = 10;
The above statement will copy the value “10” to the address of variable a pointed to by the pointer “ptr1”. The above assignment statement can be written in another way as shown below:
Printf ( “ % d \n ”, *ptr1 );
The above statement will also print the value stored in the pointer on the screen as output.
Pointers are very much essential nowadays in programs. They solve basically two problems avoiding many other problems that may follow. First problem that they solve is that they make it easy to share information and data through and from the different sections of the memory. Secondly, they solve the problem of having complex structures. They make it easy to have linked data structures namely linked lists and queues and also binary trees. Pointers reduce the complexity of the program and there are many things that one can do using only pointers. Pointers are by no doubt a powerful C construct.
Posted by
Sunflower
at
10/06/2011 06:17:00 PM
0
comments
Labels: C, C Language, Compiler, Complex, Complexity, Data, Functions, Memory, Objects, Pointers, Points, Programs, Storage, Structures, Values, Variables
![]() | Subscribe by Email |
|
Wednesday, October 5, 2011
Some details about Pointers to Arrays in C
A pointer is a variable that holds a memory address, usually of another variable in memory. The pointers are one of the most powerful and strongest features of C language. The correct understanding and use of pointers is critical to successful programming in C. pointer’s support C’s dynamic memory allocation routines. Pointers provide the means through which the memory location of a variable can be directly accessed and hence can be manipulated in the required way. Lastly, pointers can improve the efficiency of certain routines. Arrays and pointers are very loosely linked. C treats the name of array as if it were a pointer.
Consider the following code snippet:
Int *a ; // a is a pointer to an integer
Int age [10] ; //age is an array holding ten integers
For (int I = 0; I < 10 ; I ++)
a = age ; // makes a to point to the location where age points to. Age is a pointer pointing to age [0].
.
.
.
In the above code a is a pointer and age is an array holding 10 integers. The pointer a is made to point where age is pointing to. Since the name of an array is a pointer to its first element, the array name + 1 gives the address of the second element of the array, array name + 2 gives the address of the 3rd element, and so forth.
Pointers also may be arrayed like any other data type. To declare an array holding 10 integer pointers, the declaration would be as follows:
Int *ip [10] ; // array of 10 int pointers
After this declaration, contiguous memory would be allocated for 10 pointers that can point to integers. Now each of the pointers, the elements of pointer array, may be initialized. We can use the following statement:
Ip [3] = &a ;
To find the value of a, you can use the below given statement:
*ip [3] ;
The name of an array is actually a pointer to the first element of the array, the same holds true for the array of pointers also. Most often, an operation is carried on successive elements of an array. Using a loop for it and using the array elements indices. Consider the following code fragment that initializes an array to 0:
Const int abc = 20 ;
Int arr [ abc ] ;
For ( int I = 0 ; I < abc ; i++ )
Arr [ I ] = 0 ;
To execute the above code snippet, the compiler computes the address of array [ I ] every time by multiplying the index I by the size of an array element. That is, the compiler performs the multiplication for each element. A faster alternative would be to use a pointer as shown below:
Const int abc = 20 ;
Int arr [ abc ] ;
Int * arr2 ;
For ( arr2 = arr ; arr2 < &arr [ abc ] ; arr2++ )
*arr2 = 0;
Now the compiler only needs to evaluate a subscript once, when setting up the loop, and so saves 19 multiplication operations. So it is faster to use an element pointer than an index when you need to scan the arrays in a program. Pointers in c are defined by their data type and values. The data type determines the increment or decrements of the pointer value. The value is the address of the memory location to which the pointer is pointing. If you are using array notation, you don’t need to pass the dimensions.
Posted by
Sunflower
at
10/05/2011 07:45:00 PM
0
comments
Labels: Address, Arrays, C Language, Code, Data, Efficiency, Function, Integer, Memory, Pointers, Programming, Routines, Structures, Variables
![]() | Subscribe by Email |
|
Thursday, September 15, 2011
Some details about Pointers and Structures in C...
A pointer can be defined as a variable pointing to another variable or a variable storing the location or address of another variable.Pointers can be used to point to any data type.There are object pointers, function pointers, structure pointers and so on. Like any other pointers, structure pointers are also a very useful tool in C programming.Pointer structures are easy to declare and declared similarly like any other kind of pointer by putting a “*” sign before the name of the structure. See the example below:
Struct address *a1, *a2;
a1 = &b2;
a2 = &b3;
where b2 and b3 are the actual structure address variables. Using the below given assignment statement you can copy the details of structure pointed by a2 to a1:
*a1 = *a2;
Any member of a structure can be accessed using a pointer in the following way:
A->b
Here A is a pointer pointing to a structure and b is a data member or a member function of the structure being pointed. And there’s another way to access a member of a structure which has been given below:
(*A).b;
Both the statements are equivalent. Use of structure pointers is very common and useful.Be careful while dealing with structure pointers like any other normal pointer.The precedence of operators matters a lot. Be careful with the precedence of operators while programming in C.If we enclose *A is parentheses, an error will be generated and the code will not be compiled since the “.” Operator has got a high precedence than the”*” operator.Using so many parentheses can be quite a tedious job so, C allows us to use a shorthand notation to reduce the bombastic jargon. ” (*A).” can also be written as given below:
A ->
This is equivalent to (*A). but takes less characters. We can create pointers to structure arrays. A lot of space can be saved if we declare an array of pointers instead of an array to structures. In this only one structure is created and subsequently values are entered and disposed. Even structures can contain pointers as shown below:
Typedef struct
{
Char a[10];
Char *b;
} c;
c d;
char e[10];
gets(d.a,10);
d.b = (char *) malloc (sizeof (char[strlen(e)+ 1]));
strcpy(d.b, e);
This method is implemented when only a few records are required to be stored. When the size of the structure is large, it becomes difficult to pass and return the structures to the functions. To overcome this problem we can pass structure pointers to the functions. These structures can be accessed indirectly via pointers. Given below is a small code to illustrate the passing of structure pointers to the function and accessing them:
struct product
{
Int pno;
Float price;
};
Void inputpno (struct product *pnoptr);
Void outputpno (struct product *pnoptr);
Void main()
{
Struct product item;
Printf(“product details\n\n”);
Inputpno (&item);
Outputpno (&item);
}
Void outputpno (struct product *pnoptr)
{
Printf( “product no. = %d, price = %5.2f \n”, ( *pnoptr). Pno, (*pnoptr).price);
}
Void inputpno (struct product *pnoptr)
{
Int x;
Float y;
Struct product pno;
Printf( “product number: “);
Scanf( “%d”, &x);
( *pnoptr).pno = x;
Printf ( “price of the product: “);
Scanf( “%f”, &y);
( *pnoptr). Price = y;
}
In this program code, the prototypes, function calls and definitions have been changed in order to work with structure pointers. Dereferencing of a structure pointer is very common in programs. “->” (arrow) is an operator that is provided by C for accessing the member function of a structure. The 2 statements given below are equivalent:
Pnoptr -> pno;
(*pnoptr).pno;
Posted by
Sunflower
at
9/15/2011 08:44:00 PM
0
comments
Labels: Arrays, C, C Language, Code, Compilation, Definitions, Details, Functions, Input, Output, Pointers, Programming, Prototypes, Statements, Strings, Structures
![]() | Subscribe by Email |
|
Wednesday, September 14, 2011
Some details about pointers and strings in C...
There doesn’t exist anything in C like real strings. A string is an array. It can be defined as an array of characters. A string is terminated by a nul character “\0”. A string can be initialized normally as follows:
Char string[10];
String[0] = ‘c’;
String[1] = ‘a’;
String[2] = ‘t’;
String[3] = ‘s’;
Another way of initializing and declaring a string is as follows:
Char string[10] = “cats”;
The following statement asks compiler to allocate 10 bytes of memory for the string entered by the user. The string can store only 9 characters and the tenth one being used for “nul” character.
We can easily access strings and their constituent characters using character pointers. The string arrays are mostly used for storing char data type elements in the memory. The array of string pointers is preferred over two dimensional arrays of characters mainly for two reasons. The first reason is by implementing array of pointers, you can make more efficient use of available memory since it consumes lesser number of bytes for storing arrays of strings. The second main reason is that an array of string pointers makes the manipulation of strings easier. You can easily exchange the positions of strings in the array using pointers without touching their memory locations. This makes managing strings very convenient. Another way of initializing a string is by using pointers like
for example:
Char string[ ] = “cats”;
Char *a;
Here is a pointer pointing to the string “string”. Pointers are another suitable way to access string arrays and modify them as we want. Since strings are composed of characters, we should use pointers to characters. The types of the variable and the pointers must match otherwise an error will be generated. Be careful that you don’t use “&” (address of) operator to assign the address of a variable to the desired pointer. If you used it, the name of the array will be used as the address of that particular array. For this reason only we do not use “&” (address of) while passing a string to the function scanf(). For example see the following code:
Int a;
Char name[10];
Scanf(“%d%s”, &a, name);
The pointer allows us to access the required character in the string because we made it to point to that string. Functions can be passed to print labels and to call the function. Below is an example:
Void printlbl(char lbl[ ])
{
Printf (“the label: %s\n”, lbl);
}
int main()
{
char lbl2[] = "abc";
Printlbl(lbl2);
}
Now if we want to pass a pointer to the string array lbl2, we will use the following code:
Char *lblptr = lbl2;
The above declared pointer can be used in the function also like shown below:
Printlbl (lblptr) ;
After execution you will observe that both the statements give the same output. Now you will ask me why so? The answer for this is that when we pass an array as a parameter or an argument to a function, a pointer is automatically created without we knowing it and the arrays are passed by reference method automatically the way a pointer is passed. So the above written code can also be written the other way as follows:
void Printlbl(char *lbl)
{
printf("the Label: %s\n",lbl);
}
a code for dynamically allocated string is given below:
string = (char *)malloc(sizeof(char) * (len+1));
Some stings can be allocated dynamically. This is done when we don’t know how much long a string will go until the program is executed or when we don’t what size of string the user will enter.
Posted by
Sunflower
at
9/14/2011 09:01:00 PM
0
comments
Labels: Arrays, C Language, Characters, Code, Compiler, Data types, Declaration, Errors, Functions, Initialization, Memory, Pointers, program, software engineering, Strings, Variables
![]() | Subscribe by Email |
|
Tuesday, September 13, 2011
Some details about the types of pointers and arrays in C
Arrays are linear data structures whose data elements form a sequence. The elements of these linear structures are stored in memory as the contiguous memory locations and are represented as the same. These are the simplest data structures and are easy to be performed operations like insertion, deletion, searching, and traversal, sorting and merging. An array can store a finite number of data elements homogenous in nature i.e., they should be of same data type. The number of elements of the array represents the length or size of the array. The front and end index of the array are called lower bound and upper bound respectively. In C, the lower bound is always 0 and the upper bounds calculated as (size – 1). There are basically two types of arrays namely one dimensional arrays, two dimensional arrays and multi-dimensional arrays. The one –dimensional arrays are the simplest ones. Every name has a unique name. Each element of the array is represented by an index number or subscript of the element. An array is represented as:
Array name[ lower bound L, upper bound]
One - dimensional elements are implemented in C by allocating a sequence of contiguous memory location. The starting address of the first element of the array is called the “base address” of the array. C allows many searching algorithms namely linear search and binary search.
Two dimensional arrays are the arrays in which each element is itself an array. For example, a two dimensional array “A” can be represented as a table of M*N elements, where M is the number of rows and N is the number of columns. These arrays also like one dimensional array are stored as contiguous memory allocations. They must be linearized before storing.
These two dimensional arrays can be implemented in two ways i.e., row- major and column major. Row major implementation technique stores the arrays as rows whereas column major implementation technique stores arrays as columns i.e., it stores first row of the array as the first column in the memory. Algebraic Operations that can be performed on two- dimensional arrays are addition, subtraction, multiplication, division and transposition.
Pointer is a variable which stores the address of another variable. Pointers are the strongest as well as the weakest feature of the C programming language. Pointers are a mean to access and modify the address of a variable and its value. Pointers provide a way to implement dynamic allocation of memory and to improve the efficiency of program routines. But, they have a downside which is that they can cause your system to crash or hang if used in an incorrect way. There are no real arrays in a C program, but a chain of pointers. The name of the array is itself a pointer pointing to the first element of the array. There are many kinds of arrays. We will discuss them one by one. First is “array pointers”. These pointers store the address of the first element of the array. An array pointer can be declared as follows:
Int *a[10];
The second kind of pointers is “string arrays”. Strings as we know are nothing but just arrays of characters. A character pointer can be declared as:
Char name[ ]=”abc”;
Char *cpr;
The third type of pointer is called “const pointer” and can be defined as the constant pointer or a pointer to a constant. The fourth type of pointers is known as “structure pointers”. These pointers point to the structures. They too are declared by placing “*” in front of a structure name. Fifth type of pointer is called “object pointer” and points to an object the last and sixth type of pointer is the “THIS pointer” and it is used to automatically pass an implicit argument or a pointer to the object invoked in the function call.
Posted by
Ashish Agarwal
at
9/13/2011 11:18:00 PM
0
comments
Labels: Arrays, C Language, Engineering, Pointers, Software development, software engineering, String Arrays
![]() | Subscribe by Email |
|
Friday, September 9, 2011
Understanding the Structure of a C Program
The best way to get started with any programming language is to study a program, so in order to make you understand C program structure, we will take into consideration an example program whose code is:
1. /* this is a simple c program
2. Written to explain basic program structure */ -------------------------multiple line comment
3. #include
4. int main()
5. {
6. return 0;
7. }
This is the simplest C program and this program unfortunately doesn’t do anything. “#include
Functions are the basic building blocks of any program. The function “main()” is the most important function in any C program. You can say that this is the point of execution of a program. This function should exist as an entry point. Following the main is a pair of parentheses. These two parentheses indicate that the main is a function. Now coming to the opening and closing pair of braces in lines 5 and 7, are used to define the limits of a function or the program. Usually these braces contain executable statements of a function. The main() is preceded by word int. it means that this function returns an integer value. This value is returned using the “return” statement.
Now let’s take a program “abc.C” that does something. It’s same as the previous except that it has an executable statement between the braces in addition to the obligatory return statement. The executable statement calls a function which is already included in the header files as a part of the C library. The function is namely “printf()” and in order to make it print text the desired text is written with quotation marks within the parentheses of the function. The text will be displayed on the monitor when program is run. Notice the semicolon at the end of the executable statements. A semi colon in C is used as a statement terminator.
Consider the following statement:
printf("Hello World!\n");
Notice the “\n” character. The back slash is used to indicate to the compiler that a special character is being inserted. Here “n” indicates a new line. This is used whenever you want to print something in a new line. The function “printf()” prints the text and returns the carriage. Consider the following statements:
int index;
the key word int stands for integer and is used to declare a variable of type integer called index. Always keep in mind that the number of field descriptors and the number of variable definitions must be the same or else the runtime system will generate something we are not expecting. Another common and important part of C program structure is “comments”.Comments are optional but it’s good to include because they make the program more readable although they don’t mean anything to the compiler. Comments are of two types: single line comments and multiple line comments. Single line comments are used to give only one line description of a function or any other statement. A multiple line comment spans through several lines and is used to give a detailed description of a program or function.Look at the above program code for an example of comments. Another important part of a program are statements and expressions which combine variables and constants and can be assignments, function calls etc.Coming to the line breaks they are necessary to for good style formatting of your programs. This makes it easy for you to understand how your program flows when you want to maintain or modify it.You can also use “blank lines” after pre compiler declarations and declaration of new variables.Indentation should also be used in order to make your program more readable and to define the body of functions.
Posted by
Sunflower
at
9/09/2011 10:04:00 PM
0
comments
Labels: C, C Language, C program, Characters, Code, Compilation, Constants, Define, Functions, Languages, program, Statements, Structure, Values, Variables
![]() | Subscribe by Email |
|
Thursday, September 8, 2011
How is program controlled in C?
Every program follows a control path. C program control constructs are conditionals and loops. Almost every program needs to go through some sort of decision making. Decision making processes are simulated in C using conditionals. We can state a conditional as a statement that instructs the compiler to execute a function or statement if a certain condition is proved true. Decision making is done on the basis of some logic. Logic is treated as arithmetic by C compiler. The value 0 stands for true and rest any other value stands for a false value. The most common conditionals are if-else statements, switch case statements and loops.
If-else statements are used for conditional branching. It starts with if followed by an expression in its parentheses. The enclosed expression is evaluated and if the condition proves out to be true the succeeding statement is executed. If the condition is false the succeeding statement is skipped. Break and continue statements are used in if else and switch case constructs. Break will cause the execution to jump out of the loop and execute the following immediate statements whereas continue statement causes the loop to execute again and again until the condition is proved false.
Switch case begins with keyword switch followed by a variable to be switched enclosed in a parentheses. The word case is used to begin each case followed by a variable for that case, then a colon and then by the statements to be executed. Statements will be executed until a break is found. Any of the above constructs can be nested. Now coming to the go to statement, with this goto statement you can jump in between anywhere in a program except you are not allowed to jump in a loop. Goto statements are mostly risky but if there’s a place in the program where a goto statement fits , feel free to use it. However you should not be used.
Let’s define the loops now. C has 3 types of loops namely the while loop, for loop and the do while loop. The “while loop” continues to execute till the condition proves to be false. It’s an entry controlled loop which means that the loop will execute only when the condition is met. In this loop the keyword while is followed by some expression in parentheses, followed by a compound statement enclosed in braces. After reaching at the end of the loop, the control goes back to the top and the condition is revaluated.
Do while loop is an exit controlled loop. The test condition is evaluated at the end only. So even if the condition is false the loop is executed once compared to the while loop which doesn’t allows execution even once if the condition is false. You can call the do while loop as a pos check loop. This is the main difference between the while loop and the do while loop. These loops can also be nested. Nesting is unlimited. The “for loop” is the easiest loop. All its loop controlled elements are gathered at one place while in other loops they are scattered everywhere in the program. In a for loop firstly the initialization expression is executed. Then, the test expression is evaluated. If it’s true, the body of the loop is executed. After the execution the update expression is implemented, the test expression is again evaluated. If it’s true the whole sequence is repeated. You should use a for loop hen you have to repeat a block of statements specific number of times. These are the tools that programs need to perform repetitive tasks and make decisions.
Posted by
Sunflower
at
9/08/2011 06:42:00 PM
0
comments
Labels: Branching, C, C Language, Compiler, Conditions, Constructs, Control, Logical, Loops, Paths, program, Program control, Statements
![]() | Subscribe by Email |
|
Wednesday, September 7, 2011
How are strings and arrays defined in C?
A string can be defined as a group of characters, usually letters of the alphabet. When C is either to compare a string with another string, output it, copy it to another string, or whatever, the functions are intended to do what they are called to do until a null, which is a zero, is detected. Such strings are often called an ASCII-Z string. C treats a string as an array termination with a NULL character. C does not have a separate data type for strings and so strings exist as the arrays of characters. An extra byte must be left to store the NULL “\0”. Strings are declared as the arrays of characters. For example:
char name[25];
Strings can be fully or partially initialized depending on the requirements of the user. For example:
char fill[10] = { ‘a’, ‘ ‘, ‘r’,’o’,’p’,’l’,’a’,’n’,’e’,’\0’ };
There exist certain predefined functions for modifying strings. The library cstring.h houses all these functions. Strcpy() is used to copy one string into another string. Strlen() is used to determine the length of the string. Strcmp() is function for comparing two strings i.e., which one is bigger in terms of length. Strcat() is used to concatenate two strings. The second string is appended to the end of the first string. Strrev() is used to reverse a string alphabetically.
An array is a C derived data type and can be defined as a collection of variables of the same data type that are referenced by a common name. All arrays consist of contiguous memory locations where the lowest address corresponds to the first element and highest address corresponds to the last element. Arrays are useful when quite many elements of the same data type are needed to be stored and processed. The numbers in [ ] are called indices or subscripts. A string itself is an array of characters. Arrays are of two types namely one- dimensional arrays and multi dimensional arrays. Multi dimensional array comprises of elements which themselves are arrays. The general form of an array declaration is as follows:
Type array-name [size];
Here type states the data type of the array elements. The array name declares the name of the array, and finally the size defines how many elements will be there in the array. The data type of the array is called the base type.
A multidimensional array consists of M*N elements where M is the number of rows and N is the number of columns. It can be declared as follows:
Type array-name [rows][columns];
Where single dimensional arras can be read using a single loop, it takes nested loops to read and access the elements of a multi dimensional array. One loop is used to process the rows and the other one is used to process the columns. The arrays can be initialized during the run time as follows:
Type array-name [size 1]……….[size N]= {value list};
The value list consists of the array elements. C allows you to skip the size of arrays in an initialization statement. These types of arrays are called unsized arrays. For example:
Int abc[ ] = {1,2,3,5,7};
The best way to assign values to an array is using a "for" or "while" loop because it’s not affordable to write a separate initialization for every element. Arrays can be passed s parameters to the functions to maintain a structured design. Always keep in mind that in C subscripts start from 0. A string from an array of strings can be accessed by using pointers. But keep in mind that pointers hold only address of the strings. From there it is able to obtain the whole chunk of the contiguous memory.
Posted by
Sunflower
at
9/07/2011 06:35:00 PM
0
comments
Labels: Arrays, C, C Language, Characters, Copy, Data, Elements, Functions, Initialization, Length, Letters, Nested loops, Null, Output, Requirements, Size, Strings, User, Values, Variables
![]() | Subscribe by Email |
|
Tuesday, September 6, 2011
What are functions,variables and prototyping in C?
Variables or identifiers are the fundamental basic building blocks of a program. They are general terminology for objects, classes, functions, arrays etc. It can be defined as an arbitrarily long sequence of letters and digits and the first character must always be a letter. Upper and lower case letters are treated differently and all the characters are significant. C is implementation dependent. C is case sensitive as it treats lower and upper case letters differently. These are basically named storage, whose values can be manipulated during the execution of the program. There are 2 values associated with every variable namely r value and l value. The value of the variable is called r value whereas l value is the address in memory where the variable is located. Generally a variable is declared as :
type name;
A simple definition consists of a type specifier followed by a variable name. There are 2 types of variables: local variables and global variables. Local variables are declared inside a function and are available to that function only whereas global variable are declared outside main() and are available to all the functions.
A large program is difficult to manage and understand. Thus, it is broken down into different modules called functions which can be put together to form the complete program. So we can define a function as a sub program that acts on data and often returns a value. A good function contains a number of functions since it is easier to maintain update and debug. Each function has its own name. On the encounter of the function’s name in any part of the program the function is called. There are basically 2 types of functions namely built-in functions and user-defined functions. Built in functions are parts of the compiler package and are made available to the program by header files. For example: exit(), sqrt(), strlen(), size() etc. user defined functions are created by the programmer as per the requirements of the program. A function has 3 parts: function definition, function call and function prototype. In C a function must be defined before it is used anywhere. Generally a function is defined as:
type function-name(parameter list)
{
Body of the function
}
Here the type specifies the type of return value. The parameter list is the list of arguments passed to the function separated by commas. A function may be defined without any arguments or it can also have an open parameter. A function definition must have a return statement.
One of the most important features of C is function prototyping as it describes the function interface to the compiler. It can be defined as the declaration of the function that tells the program about the type of the value returned by the function and the number and type of arguments. Therefore, we can say that a prototype has following parts:
- Return type
- Name of the function
- Argument list
Function prototyping is essential as it allows a compiler to compare each use of the function with the prototype to determine whether the function has been invoked properly or not. This makes it easy for compiler to correct the errors. The function prototype and function definition must exactly agree on the function name, return type, and argument list. The prototype looks just like a function definition except that the code is missing. A prototype introduces a function to the program whereas a definition being a declaration also tells the program what the function is doing and how it is doing. C makes prototyping essential. We can skip the arguments in a prototype but not in the definition.
Posted by
Sunflower
at
9/06/2011 08:00:00 PM
0
comments
Labels: Arrays, C, C Language, Case sensitive, Classes, Compiler, Definition, Errors, Functions, Global, Identifiers, Local variables, Objects, program, Prototyping, Types, Values, Variables
![]() | Subscribe by Email |
|
What is Assignment and Logical Comparison in C...
An expression as we all know is composed of one or more operations. When the expression is terminated by a semi colon, it becomes a statement which is the small executable unit in any program. The assignment statements are used to assign a value to a variable. The assigned value can be a constant variable or an expression. An assignment statement can be written in general form as:
A=bcd;
Where A is a variable to whom we are assigning a value and bcd is the assigned value. The “=” sign is called assignment operator. Assignments can be chained together. The assigning operator “=” assigns the value to the left hand operand and returns the value of the assignment. Assignment statements are very much needed for variable initialization since variables are initialized using assignment statements. There are 2 ways to do this:
- Un-initialized variable
- Initialized variable
An un-initialized variable has to be initialized in separate statements whereas an initialized variable combines declaration and assignment in to one statement.
Examples are:
Int a;
a=3; ------------------------uninitialized variable
int a= 3; -------------------- initialized variable
Assignment also follows when you use dynamic initialization. Sometimes variables of different types are mixed with each other. It’s a very common and observed phenomenon. In such cases a type conversion takes place. Here also it follows from the principal of assignment statement that “the value of the right side of the expression or of the assignment is converted to the type of the variable on left side i.e., target variable. Both the sides of assignment should be compatible with each other for type conversion. When conversion takes place from smaller data type to a larger data type no data is lost. Precedence of operators while assigning values with an expression should always be kept in mind.
Some programs need the power of decision making or comparison. This is granted through logical expressions which are nothing but the statements resulting into a 0 (true) or 1 (false) value. These are a combination of constants, variables and logical and relational operators. Be careful that two or more variables and operators should not occur in continuation. A logical expression may contain just one signed or unsigned variable or a constant or it may have two or more also joined by varied relational and logical operators. Following are some valid logical operators: the logical OR operator (||), the logical AND operator (&&) and the logical NOT (!) operator. The OR operator combines 2 expressions as its operands. If either of its operand evaluates to true, the OR operator also evaluates to true. This operator is basically used for testing evaluating expressions. The AND operator combines 2 expressions into one and the operator evaluates to one if and only if both the operands evaluate to 1. The NOT operator works on a single operand since it is a unary operator. It is used to negate or reverse the truth value of the operand. It has a higher precedence than of the relational and logical operators. Therefore, this should be enclosed within parentheses. This operator is useful as a test for zero. OR and AND operators have lower precedence than relational operators. Relational operators are used to define relationships between variables. C provides 6 basic relational operators : < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), == (equal to), and != (not equal to). Do not confuse the = and the == operators. “=” is assignment operator whereas “==” is relational equality operator.
Posted by
Sunflower
at
9/06/2011 11:40:00 AM
0
comments
Labels: Assignment, C, C Language, Comparisons, Constants, Conversions, Declaration, Executable, Expressions, Initialization, Logical, Logical comparison, Operations, Operators, Variables
![]() | Subscribe by Email |
|
Sunday, September 4, 2011
What are C Compilers and their properties?
A compiler is a program that translates source code into object code. The compiler got its name from the way it works, checking the entire piece of source code and collecting and reorganizing the procedural instructions. Thus in this way a compiler differs from an interpreter which analyzes and executes each line of source code in succession, without looking at the entire program. Compilers require some time for producing an executable source code. However, programs produced by compilers execute much faster than the same programs executed by an interpreter. Many compilers are available for the same language. More than a dozen companies develop and sell compilers for C language. So here are some C compilers at your finger tips listed along with their properties:
1. AMPC: By Axiomatic Solutions Sdn Bhd. Supports all Operating systems. Proprietary license. not available online. Supports IDE.
2. Amsterdam Compiler Kit: By Andrew Tanenbaum and Cerial Jacobs. Works with UNIX and other OSs except windows. BSD license. Not available online. Does not support IDE.
3. Clang: By low level virtual kit. Supports all OSs. BSD license. Not available online. Does not support IDE.
4. Compiler: By Ninja Otter Inc. supports all OSs. Proprietary license. Available online. supports IDE.
5. DMS software reengineering Tool Kit: By semantic Designs. Supports all operating systems. Proprietary license. Not available online. Does not support IDE.
6. GCC: By GNU project. Supports all Oss. GPL license. Not available online. Doesn’t support IDE.
7. RCC (RCOR C compiler): By Rodrigo Caetano (rcor). Supports only windows and UNIX. GPL license. Not available online. Does not supports IDE.
8. Ideone: unknown author. Doesn’t support any OS. Freeware. available online. Does not support IDE.
9. Lab windows/ CVI: by National Instruments. All OSs. Proprietary license. Not available on web. Supports IDE.
10. Icc: By Chris Fraser and David Hanson. Supports all OSs. Freeware. Not available online. Supports IDE in windows only.
11. Mark Williams C: By Mark Williams Company. Supports all Oss except UNIX. Proprietary license. Not available online. Supports IDE.
12. Microsoft C: by Microsoft. Supports only windows. Proprietary license. Not available online. supports IDE.
13. Nwcc: By Nils Weller. Supports all OSs. BSD license. Not available online. Doesn’t support IDE.
14. Open64: By SGI Google, HP, and Intel, Nvidia, Path Scale, Tsinghua University and team. Supports all OSs. GPL license. Not available online. Doesn’t support IDE.
15. Pelles C: by Pelle Orinius. Supports only windows. Freeware. Unavailable on web. Supports IDE.
16. PGCC: By The Portland Group. Supports all OSs. proprietary license. Not found on web. Supports IDE.
17. Portable C compiler: By Anders Magnusson and team. Supports all OSs. BSD license. Not available online. Does not support IDE.
18. Power C: by Mix Software. Supports all Oss except windows and UNIX. Proprietary license. Doesn’t support IDE. Not available online.
19. QuickC: By Microsoft. Supports only windows. Proprietary license. Supports IDE. Not available online.
20. SAS/ C: Its author is SAS institute. Works with all Oss. Proprietary license. Supports IDE. Not available online.
21. Tiny C compiler: Its author is Fabrice Bellard. Supports only windows and UNIX. LGPL license. Doesn’t support IDE. Not available online.
22. Turbo C: By Embarcadero. Supports all Oss except windows and UNIX. Proprietary license. Supports IDE. Not available online.
23. CCS C compiler: By CCs, Inc. supports all OSs. Proprietary license. Supports IDE. Not available online.
24. Ups debugger: By Tom Hughes, Ian Edwards and team. Supports all Oss except windows. GPL license. Not available online. Supports IDE.
25. VBCC: by Dr. Volker Barthelmann. Supports all OSs. Doesn’t support IDE. Not available online.
Posted by
Ashish Agarwal
at
9/04/2011 10:49:00 PM
0
comments
Labels: C Language, Compile, Compiler, software engineering
![]() | Subscribe by Email |
|
Saturday, September 3, 2011
What is a C PREPROCESSOR ? Why is it important?
C preprocessor or cpp is a program that is executed prior to the execution of the compiler. It’s very important as it removes all the comments from the source and performs textual substitution based on the code and passes it to the compiler for actual compiling and it also handles directives for the inclusion of source files. Consider the following statement:
#define
This is the way all macros and defines are declared. Before the start of compilation, the preprocessor resolves all of the defines. Macro is also a kind of define, but it is capable of appearing to perform some logical operations, math’s functions and it has a unique name. While defining a macro, it is imperative that there should be no space between the name of the macro and opening parentheses. If a space is present, it makes it difficult for the compiler to determine whether its macro or not. Instead it’ll handle it like a simple substitution define statement.
Often there are a lot of extra parentheses in a macro definition but they are extremely important. Most experienced C programmers always put parentheses around each and every variable in a macro and entire expression. This avoids error and allows any macro to work properly. A macro cannot be expanded within a quoted string, although, the arguments’ text can be quoted and that will be treated as a string literal. This can be done using “#” directive. There are macros called variadic macros which can take a varying number of arguments. They are useful when writing wrappers to variables of number functions. X macro is a header file which contains a list of similar macro calls. Macros are of two types namely object-like and function-like.
Object like macros do not accept parameters whereas function like macros do. Function like macro should not have a whitespace between the variable and the opening parentheses. Presence of a whitespace will make the compiler treat it as an object like macro. Object like macros are conventionally used to create symbolic names for constants and are generally considered as part of good programming. You can extend a macro across many lines by using a back slash escape sequence at the end of every line. The ternary conditional operator “?:” is also a function like macro. Token pasting or concatenation is another very easy to abuse feature of C preprocessor. Using this we can join together two arguments using ## preprocessor. This is basically used to create more elaborated macros. Multiple statements macros must be avoided as far as possible because they can show unexpected behavior. We can make a macro safe by replacing the semicolon with comma since it has lowest precedence.
Conditional compilation is a very useful construct and is used to include a feature if we are using a certain processor, a certain operating system and certain hardware. The following are the directives that can be used for conditional compilation: #if, #ifdef, #ifndef, #else, #elif and #endif. More trivial programs are too large and cannot be place within a single file and it becomes very cumbersome to work with. Therefore, it becomes very necessary for these files to work and communicate together as one large program.
What do we mean by pragma? It’s a kind of instruction to the compiler to perform a particular action at the time of compilation. The pragmas vary from compiler to compiler since they are not standardized. If the compiler provides a source listing file, then it does have pragmas to format output. #ptragma is used suppress specific error messages, to stack debugging and to manage heaps.
Posted by
Ashish Agarwal
at
9/03/2011 12:10:00 AM
0
comments
Labels: C Language, Explanation, Preprocessor, Software, Software theory, Theory
![]() | Subscribe by Email |
|
Sunday, August 28, 2011
Assignment and logical comparison in the C language
It is necessary to understand how C expresses logical relations. C treats logic as being arithmetical expression. The value 0 (zero) represents false, and all other values represent true. Code written by people uncomfortable with the C language can often be identified by the usage of #define to make a "TRUE" value. Because logic is arithmetic in C, arithmetic operators and logical operators are one and the same. there are a number of operators that are typically associated with logic:
Relational and Equivalence Expressions:
a < b
1 if a is less than b, 0 otherwise.
a > b
1 if a is greater than b, 0 otherwise.
a <= b
1 if a is less than or equal to b, 0 otherwise.
a >= b
1 if a is greater than or equal to b, 0 otherwise.
a == b
1 if a is equal to b, 0 otherwise.
a != b
1 if a is not equal to b, 0 otherwise
C does not have a dedicated Boolean type as many other languages do. 0 means false and anything else true. Often #define TRUE 1 and #define FALSE 0 are used to work around the lack of a Boolean type. It is a better idea to indicate what you are actually expecting as a result from a function call, as there are many different ways of indicating error conditions, depending on the situation. Another thing to note is that the relational expressions do not evaluate as they would in mathematical texts.
Logical Expressions
a || b
when EITHER a or b is true (or both), the result is 1, otherwise the result is 0.
a && b
when BOTH a and b are true, the result is 1, otherwise the result is 0.
!a
when a is true, the result is 0, when a is 0, the result is 1.
C uses short circuit evaluation of logical expressions. That is to say, once it is able to determine the truth of a logical expression, it does no further evaluation. we need not worry here about trying to access an out-of-bounds array element if it is already known that i is greater than or equal to zero.
Bitwise Boolean Expressions:
The bitwise operators work bit by bit on the operands. The operands must be of integral type. The six bitwise operators are & (AND), | (OR), ^ (exclusive OR, commonly called XOR), ~ (NOT), << (shift left), and >> (shift right). The negation operator is a unary operator which precedes the operand. The others are binary operators which lie between the two operands. The precedence of these operators is lower than that of the relational and equivalence operators; it is often required to parenthesize expressions involving these operators.
Assignment of values:
Programmers should take special care of the fact that the "equal to" operator is ==, not =. This is the cause of numerous coding mistakes and is often a difficult-to-find bug, as the expression (a = b) assigns a a value equal to b and subsequently evaluates to b; but the expression (a == b), called equality operator, checks if a is equal to b. It needs to be noted that, if you confuse = with ==, your mistake will often not be brought to your attention by the compiler. A statement such as if (c = 20) {} is considered perfectly valid by the language, but will always assign 20 to c and evaluate as true. A simple technique to avoid this kind of bug is to put the constant first.
Posted by
Ashish Agarwal
at
8/28/2011 12:20:00 AM
0
comments
Labels: Assignment, C, C Language, Languages, Logical comparison, Software, Software theory, Theory
![]() | Subscribe by Email |
|