Monday, October 22, 2012

Operators In 'C' :

Assignment (=)Case :- Lvalue Errormain(){int a = 10 , b = 20;printf("a=%d b=%d\n",a,b);b= ( a*b/a=b );printf("a=%d b=%d\n",a,b);}O/p:- Invalid Lvalue In AssignmentThe Above Error Is A Result Of Assignmenta*b/a=b . a*b/a is a Constant and not a value which could hold an address , but we were trying to assign a variable b to it .b=(a*b/(a=b)); Grouping a=b Using parentheses Will Solve The Issue And Makes It More Readable .Arithmetic ( + , - , * , / , % )Note :- % Operator Is Applicable Only On Integer Data TypeCase :- Type Castingmain(){int a=5,b=2;float c;c=a/b;printf("%f",c);}O/p: - 2.000000Note :- Observe The Output Is Not 2.500000 as Expected . Its because , both a and b are integers ,any operation on them results in an integer but not a higher data type .The Solution To Above Problem Is "Explicit Type Casting"

8 18 29Conditional Operator ((Condition)?(If True) : (If False))Eg :-main(){int a=10,b=20,c;(a==b)?(c=1):(c=0);printf("c=%d\n",c);a=20;(a==b)?(c=1):(c=0);printf("c=%d\n",c);}O/p:- c=0 c=1The Other Operators like &,* will be discussed in future posts.Example To Ease Your Understanding Of Operators In 'C' :Eg:- Program To Test A Given Bit In A Given Locationmain(){int num,bit;printf("Enter An Integer :");scanf("%d",&num);printf("Enter The Bit Position To Test:");scanf("%d",&bit);((num>>bit)&1)?printf("Bit is Set"):printf("Bit is Clear");}O/p :- Enter An Integer : 5Enter The Bit Position To Test: 2 Bit is SetEnter An Integer : 5Enter The Bit Position To Test: 1 Bit is Clear

Case :- Comma Operator (,)

main(){int a=1,b=10,c;C=(a= -1 , ++b , a = a+b);printf("%d %d %d\n",a,b,c);}O/p:-10 11 10The Right Most Expression Is Evaluated And Finally The Result a assigned Toc