Smile

Sunday, June 26, 2011

Expressions in C & Precedence and associativity of Operators

Expressions in C are basically operators acting on operands. Statements like a = b + 3, ++z and 300 > (8 * k) are all expressions. Strictly speaking, even a single variable or constant can be considered an expression. You have seen several expressions in the previous C tutorial on Operators in which the examples involved expressions

Precedence and Associativity

When an expression can be interpreted in more than one way, there are rules that govern how the expression gets interpreted by the compiler. Such expressions follow C's precedence and associativity rules. The precedence of operators determine a rank for the operators. The higher an operator's precedence, the higher “binding” it has on the operands.

For example, the expression a * b + c can be interpreted as (a * b) + c or a * (b + c), but the first interpretation is the one that is used because the multiplication operator has higher precedence than addition.

Associativity determines the grouping of operations among operators of the same precedence. In the expression a * b / c, since multiplication and division have the same precedence we must use the associativity to determine the grouping. These operators are left associative which means they are grouped left to right as if the expression was (a * b) / c.The operators' order of precedence from highest to lowest and their associativity is shown in this table:

Identifier, constant or string literal, parenthesized expression

[] func( arglist ) . -> ++ --

Left associative

++ -- & * + - ~ ! sizeof

Right associative

(type-name)

Right associative

* / %

Left associative

+ -

Left associative

<< >>

Left associative

< <= > >=

Left associative

== !=

Left associative

&

Left associative

^

Left associative

|

Left associative

&&

Left associative

||

Left associative

?:

Right associative

= *= /= %= += -= <<= >>= &= ^= |=

Right associative

,

Left associative


Example #1
int i=2,j=5,k=6,g;
g = i+j*k;

In the above example the evaluation will be taken place in the following way
There are two operators + * Among these two * is having highest precedence. So j*k is evaluated first 5*6=30 Then addition i+30=2+30=32. Final value of g is 32.

Example #2
int x=5,y=30,z=10,w;
w=x*y/z;

Here In the above example * / both are having same precedence. So evaluation is done in left associativity. x*y is done first 5*30=150 then 150/z = 150/10 = 15. The value of w is 15.

Example #3
int i=2,j=5,k=6,g;
g = (i+j)*k;

Here In the above example
There are three operators + * () Among these three () is having highest precedence. So
i+j is evaluated first 2+5 = 7 Then 7*k = 7*6 = 42. So final value of g is 42.

Friday, June 24, 2011

C operators

C programming language provides several operators to perform different kind to operations. There are operators for assignment, arithmetic functions, logical functions and many more. These operators generally work on many types of variables or constants, though some are restricted to work on certain types. Most operators are binary, meaning they take two operands. A few are unary and only take one operand.

Arithmetic Operators
Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*) and division (/) operations. In addition there is the modulus operator (%) which gives the remainder left over from a division operation.
Example Program

Relational Operators
Relational operators compare operands and return 1 for true or 0 for false. The following relational operators are available

Symbol Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Example

int a=35,b=90,c;

c=a < b;

The value of c after execution of above code is 1 since the condition 35 < 90 is true

C Logical Operators
The logical operators are || for a logical or and && for a logical and and ! for logical not. The and and or operate on two boolean values of true or false. In C, an expression that evaluates to 0 is false and an expression that evaluates to non-zero is true. These operators return 1 for true or 0 for false.

The following table shows the results of applying these operators to different boolean values

Left Operation Right Result

True && True True
False && True False
True && False False
False && False False
True || True True
False || True True
True || False True
False || False False

As you can see from the table, an and operation is true only when both its operands are true. An or operation is true if either one of its operands is true.

The table also shows that these operators can do what is called “lazy evaluation” or “short circuit evaluation”. The operands are evaluated from left to right. For an and operation, if the left operand is false, the right operand is not even evaluated because the result is known to be false. For an or operation, if the left operand is true the right operand is not evaluated because the result will be true.

Example
int x=55,y=67,z=55,w;
w=(x==z)&&(x>y);

The value of w from the above code is 0 since 55==55 is true but 55>67 is false
true && false = false.

Assignment Operators

C has several assignment operators available - one simple assignment operator and several convenience assignment operators that combine arithmetic or bitwise operations with assignment. The operators are as follows:


Symbol Meaning
= Assignment
*= Multiply and assign
/= Divide and assign
%= Modulo and assign
+= Add and assign
-= Subtract and assign

Example #1
int a,b=33;
a=b;

Example #2
int a=100,b=50;
a+=b;

In the second example a+=b means a=a+b which is evaluated as
a=100+50 which is 150.

Conditional operator (or) Ternary Operator

The conditional operator is unusual in that it takes three operands. The syntax of this operator is like this:


Condition ? Expression1 : Expression2;


You can think of the conditional operator as if it were a function that works like this:

if ( Condition )

return Expression1;
else
return Expression2;

The Condition expression must evaluate to true or false. If it is true Expression1 is evaluated and its value is returned. If Condition is false Expression2 is evaluated and its value is returned. Both Expression1 and Expression2 must be the same type (or convertible to the same type).

Example
int a=101,b=50,c;
c=a>b?10:20;

In the above code the value of c will be 10 as the condition 101>50 is true.

Tuesday, June 21, 2011

C constants

Constants
A constant is an entity whose value does not change throughout the program execution.
There are two types of constants
1)Numerical constants
2)Character constants

Numerical constants

The constants which are in number format is said to be numerical constants
These are of two types
a)Integer constants
b)Floating point constants

Integer constants
These are normal numbers whose range depends on data type
Ex:-
int a=3453;
long l=2300000;

Floating point constants
These are decimal point numbers. The range of these variables depends on data type.
Ex:-
float f=34.78;
double d=2367.7654;

Character Constants


Character set

The character set in C Language can be grouped into the following categories.

1. Letters
2. Digits
3. Special Characters
4. White Spaces

White Spaces are ignored by the compiler until they are a part of string constant. White Space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers.

C Character-Set Table


Letters


Digits


Upper Case A to Z


0 to 9


Lower Case a to z


.

Special Characters

,


.Comma


&


.Ampersand


.


.Period


^


.Caret

;


.Semicolon


*


.Asterisk


:


.Colon


-


.Minus Sign


?


.Question Mark


+


.Plus Sign


'


.Aphostrophe


<


.Opening Angle (Less than sign)


"


.Quotation Marks


>


.Closing Angle (Greater than sign)


!


.Exclaimation Mark


(


.Left Parenthesis


|


.Vertical Bar


)


.Right Parenthesis


/


.Slash


[


.Left Bracket



.Backslash


]


.Right Bracket


~


.Tilde


{


.Left Brace


-


.Underscore


}


.Right Bracket


$


.Dollar Sign


#


.Number Sign


%


.Percentage Sign . .
Keywords in C language
The keywords are reserved words which are already registered in C library. These words cannot be used as identifiers in the program. There are basically 32 keywords in C language. They are
auto .else .register .union
.break .enum .return .unsigned
.case .extern .short .void
.char .float .signed .volatile
.const .for .size of .while
.continue .goto .static .
.default .if .struct .
.do .int .switch .
.double .long .typedef .

Monday, June 20, 2011

C variables

Definition
A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer.

Naming Variables

The name of variable can be called identifier or variable name in a friendly way. It has to follow these rules:

  • The name can contain letters, digits and the underscore but the first letter has to be a letter or the underscore. Be avoided underscore as the first letter because it can be clashed with standard system variables.
  • The length of the variable name is usually 31 characters.

Declaring Variable
To declare a variable you specify its name and kind of data type it can store. The variable declaration always ends with a semicolon, for example:

int a;
char c;
float f;
int x,y,z;

The variables should be declared at the beginning lines of any block. These cannot be declared at the middle of the program or ending.

Initializing variables
You can also initialize a variable when you declare it, for example:
int count=0;
char alp='c';
float f=23.67;

Character variable value should be represented in single quotes

Monday, June 6, 2011

Basic Data Types in C

C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location.

The value of a variable can be changed any time.

C has the following basic built-in datatypes.

  • int

  • float

  • double

  • char

Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but thats another story.

int - data type

int is used to define integer numbers.

    {         int Count;         Count = 5;     } 

float - data type

float is used to define floating point numbers.

    {         float Miles;         Miles = 5.6;     } 

double - data type

double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.

    {         double Atoms;         Atoms = 2500000;     } 

char - data type

char defines characters.

    {         char Letter;         Letter = 'x';     } 

Modifiers

The data types explained above have the following modifiers.

  • short
  • long
  • signed
  • unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:

        short int <=    int <= long int             float <= double <= long double  

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:


 
Type Bytes Range
short int2-32,768 -> +32,767(32kb)
unsigned short int 2 0 -> +65,535(64Kb)
unsigned int 40 -> +4,294,967,295(4Gb)
int 4 -2,147,483,648 -> +2,147,483,647(2Gb)
long int 4-2,147,483,648 -> +2,147,483,647(2Gb)
signed char1-128 -> +127
unsigned char 1 0 -> +255
float 4
double 8
long double 12

Identifiers

"Identifiers" or "symbols" are the names you supply for variables, types, functions, and labels in your program. Identifier names must differ in spelling and case from any keywords. You cannot use keywords (either C or Microsoft) as identifiers; they are reserved for special use. You create an identifier by specifying it in the declaration of a variable, type, or function. In this example, result is an identifier for an integer variable, and main and printf are identifier names for functions.

Syntax
identifier:

nondigit

identifier nondigit

identifier digit

nondigit: one of

_ a b c d e f g h i j k l m n o p q r s t u v w x y z

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

digit: one of

0 1 2 3 4 5 6 7 8 9

The first character of an identifier name must be a nondigit (that is, the first character must be an underscore or an uppercase or lowercase letter)