Subscribe by Email


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

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.


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.


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.


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;


Sunday, September 11, 2011

Why C compilers are better than other language Compilers?

A compiler as we all know is a program that translates source code into object code so that the code becomes executable, or we can say A compiler converts high level language code into a low level language code (assembly language).A compiler performs six major operations namely preprocessing, semantic analysis,lexical analysis, code generation, code optimization and parsing.

A compiler has basically 3 main parts. First is the front end that checks the semantics and syntax of the program and the errors are reported.Second, the middle end which does the optimization removing any unwanted or bad code.The last part is called the back end which translates the middle level intermediate representation or IR into the assembly language.

Processor registers are assigned. The back end also draws the schedule for the hardware units. Today we see a number of compilers available in the market like clang, Microsoft C, GCC, etc. C is still the favorite language of many programmers in the world. What makes it so special? It is its compiler. C compiler is better than any other language because it is small in size, so that you can execute a program everywhere. The C compiler is usually faster than any other language compiler. Furthermore there is no overhead byte code generated.

- You can use the dynamic C library directly.
- Most of the C compilers include memory and bound checker.
- Many C compilers are capable of running under windows XP and windows Vista and are also able to compile the command line.
- Most of them support integrated environment.
- C compilers are capable of handling multi- threaded programming and are good for exploiting dynamic parallelism which otherwise can make it difficult for passing messages.
- C compilers are algorithmic in nature and provide a scheduler to schedule the performance of the programs.
- They compile and link the codes very fast and they have a very powerful optimization technology.
- They come with a library source which is complete and brows able.
- They do extensive checking during the process of compilation.
- Some C compilers are safe from the risk of pointers and are capable of fast prototyping of the programs.
- They also don’t allow violation of array bonding.
- They can be run as interactive or non- interactive phases.
- They support enumerated data types, all data type variables like int, long, and float etc. some may also provide you with some sample programs to help you understand the features of the language.
- They are perfect for parallel computing. Global vectorization and optimization is also supported.
- These C compilers do inter procedural analysis. While doing optimization they give the user necessary feedback. They are able of transferring loops.
- C compilers are capable of code generation and give optimal performance from the processors.
- They simplify the execution thus, accelerating it. No limitations are imposed code size and optimization. They are very fast and accurate as compared to the compilers of other languages.
- Latest compilers are capable of building internet, distributed and windows applications. The code generation includes compiling, assembling, linking, resource compiling and adding library files.
- The integrated development includes editing, debugging, generating files and resource editing.
- They come with documentation and user’s manual.
- Most of the C compilers don’t come as freeware.
- C compilers require Windows 95 and other latest versions for implementing command lines.
- If a C compiler is supporting IDE, you need to have windows 2000 and following versions. The system should have a minimum of 32 MB of RAM and 500 MB of ROM.

We can say they are like many in one package which allow writing, developing, compiling, interpreting, assembling and debugging, and execution of the programs.


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 //header file. ---------------------- single line comment
4. int main()
5. {
6. return 0;
7. }

This is the simplest C program and this program unfortunately doesn’t do anything. “#include” is called a preprocessor command. It tells the compiler to do processing before the compilation. This command tells the compiler to include the header file “stdio.h” in the program.

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.


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.


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.


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.


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.


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.


Friday, August 26, 2011

What are the fundamental differences between C and C++ ?

Developments in software technology continue to be dynamic. New tools and techniques are announced in quick succession. To build today’s complex software it is just not enough to put together a sequence of programming statements and sets of procedures and modules; we need to incorporate sound construction techniques and program structures that are easy to comprehend, implement and modify. Thus the languages C and subsequently C++ were born. Since C++ is an extended version of C it forms the superset of C.
Conventional programming uses languages like C (known as procedure-oriented programming (POP)). The problem is viewed as a sequence of things to be done such as reading, calculating and printing. A number of functions are written to accomplish these tasks. The primary focus is on functions. Object-oriented programming (OOP), using languages like C++ is an approach to program organization and development that attempts to eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured programming features with several powerful new concepts.
Therefore, here we derive some basic differences between C and C++:

1. As we saw above, C follows the POP paradigm while C++ follows an OOP paradigm. So, in C the emphasis is on doing things whereas, C++ views problem in terms of objects involved rather than procedure for doing it. The emphasis is on data.
2. Data is given a second class status in C but, in C++ data is given all the priority.
3. In C global data are more vulnerable to an inadvertent change by a function whereas in C++ data is encapsulated or hidden so, secure.
4. C lacks data hiding features but C++ comes with options of data abstraction and encapsulation which makes data hiding possible.
5. C follows a top-down approach while C++ uses the bottom-up approach.
6. In C a number of functions are written to accomplish a task whereas in C++ programs are divided into what are known as objects and tied together using functions.
7. It’s not easy to add functions and data to the existing program in the case of C but it can be easily added wherever required in a C++ program.
8. C doesn’t support class concept but C++ does.
9. Structures are present in both C and C++, but behave differently. C structures do not support functions contained in them.
10. In C. input/ output processing is carried out by functions (scanf and printf). C++ uses console commands “cin” and “cout”.
11. Function overloading and operator overloading are not supported by C. So, it means polymorphism is absent in C. C++ supports polymorphism well.
12. C lacks “NAMESPACE” feature while C++ supports NAMESPACE which avoids name collisions.
13. References can be used in C++ but not in C.
14. C uses malloc() and free() commands for allocation and de-allocation of memory. C++ uses new and delete commands.
15. In C header file used in whereas it is for C++.
16. C++ programs take much more time for compiling as compared to C programs. For this reason C is commonly used.
17. C is a low-level language whereas C++ is an intermediate language.


Facebook activity