Showing posts with label operators. Show all posts
Showing posts with label operators. Show all posts

Tuesday, August 31, 2010

++ / -- and pointers operator *

++ is executed first comparing with *.

So we have to use ++ (*p)

Eg, consider strcpy() function.


char *strcpy(char *dest, const char *src)
{
char *save = dest;
while(*dest++ = *src++);
return save;
}
So here first thing that is happening in while loop is dest and src are incremented by 1
Than they are referenced by *
Then equated and finally loop moves on until it gets '\0'..i.e null

Sunday, August 29, 2010

Using == operator in better way in cpp

In cpp, it is possible that instead of
i==5

we can do

i=5

So we assign i = 5 and if it is like
if(cond)
cond gets true.

So better is
5==i
beause == is symmetric.
If someone writes by mistake is
5=i
As we get error = 'can't assign value to literal'.

Sunday, December 6, 2009

sizeof operator

1) Why is sizeof operator and not function




sizeof() is a compile time operator. To calculate the size of an object, we need the type information. This type information is available only at compile time. At the end of the compilation phase, the resulting object code doesn't have (or not required to have) the type information. Of course, type information can be stored to access it at run-time, but this results in bigger object code and less performance. And most of the time, we don't need it. All the runtime environments that support run time type identification (RTTI) will retain type information even after compilation phase. But, if something can be done in compilation time itself, why do it at run time?


2) On a side note, something like this is illegal...


printf("%u\n", sizeof(main)); 

The sizeof operator shall not be applied to an expression that has function type.


Egs.
1)

main()
{
char *p="GOOD";
char a[ ]="GOOD";
printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p),
sizeof(*p), strlen(p));
printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));
}
Answer:
sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
sizeof(a) = 5, strlen(a) = 4


Explanation:
sizeof(p) => sizeof(char*) => 2
sizeof(*p) => sizeof(char) => 1
Similarly,
sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the array
and it is not the same as the sizeof the pointer variable. Here the sizeof(a)
where a is the character array and the size of the array is 5 because the
space necessary for the terminating NULL character should also be taken
into account.





Questions on operators (increment, relational)

1)
main()
{
int i=0;

while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C. So it has no effect on the
expression and now the while loop is, while(i--!=0) which is false
and so breaks out of while loop. The value –1 is printed due to the postdecrement
operator.


main()
{
float f=5,g=10;
enum{i=10,j=20,k=50};
printf("%d\n",++k);
printf("%f\n",f<<2);
printf("%lf\n",f%g);
printf("%lf\n",fmod(f,g));
}
Answer:
Line no 5: Error: Lvalue required
Line no 6: Cannot apply leftshift to float
Line no 7: Cannot apply mod to float
Explanation:
Enumeration constants cannot be modified, so you cannot apply ++.
Bit-wise operators and % operators cannot be applied on float values.
fmod() is to find the modulus values for floats as % operator is for ints.


main()

{
int i=5,j=10;
i=i&=j&&10;
printf("%d %d",i,j);
}
Answer:
1 10
Explanation:
The expression can be written as i=(i&=(j&&10)); The inner expression
(j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the
result.



main()
{
int i=4,j=7;
j = j || i++ && printf("YOU CAN");
printf("%d %d", i, j);
}
Answer:
4 1
Explanation:
The boolean expression needs to be evaluated only till the truth value of
the expression is not known. j is not equal to zero itself means that the
expression’s truth value is 1. Because it is followed by || and true ||
(anything) => true where (anything) will not be evaluated. So the
remaining expression is not evaluated and so the value of i remains the
same.
Similarly when && operator is involved in an expression, when any of the
operands become false, the whole expression’s truth value becomes false
and hence the remaining expression will not be evaluated.
false && (anything) => false where (anything) will not be evaluated.



main()
{
register int a=2;
printf("Address of a = %d",&a);
printf("Value of a = %d",a);
}
Answer:
Compier Error: '&' on register variable
Rule to Remember:
& (address of ) operator cannot be applied on register variables.


Saturday, December 5, 2009

Find the maximum of three integers using the ternary operator.

max = ((a>b)?((a>c)?a:c):((b>c)?b:c));

Pointer indirection with care




* and . operator
struct rec
{
int i;
float f;
char c;
};

int main()
{
struct rec *p;
p=(struct rec *) malloc (sizeof(struct rec));
(*p).i=10;
}
To initialise pointer to 10, we have to use parenthesis, because . operator has higher precedence than * operator.

++ and *
Consider *p++
The postfix "++" operator has higher precedence than prefix "*" operator. Thus, *p++ is same as *(p++); it increments the pointer p, and returns the value which p pointed to before p was incremented. If you want to increment the value pointed to by p, try (*p)++. 

Friday, December 4, 2009

Operator Precedence in C & CPP

Operator Precedence Chart 
Operator Type                                  Operator                               Associativity
1. Primary Expression Operators     () [] . -> expr++ expr--        left-to-right
2. Unary Operators                        * & + - ! ~ ++expr --expr    right-to-left
                                                           (typecast) sizeof()    
3. Binary Operators                       * / %                                           left-to-right
                                                         + -
                                                          >> <<
                                                          < > <= >=
                                                          == !=
                                                         &
                                                         ^
                                                          |
                                                          &&
                                                          ||
4. Ternary Operator                            ?:                                       right-to-left
5. Assignment Operators     = += -= *= /= %= >>=            right-to-left
                                            <<=  &= ^= |=
6. Comma                                      ,                                                left-to-right

Note: 1,2,3 etc above shows the level of precedence, with 1 being of highest precedence etc.
Associativities are from left to right....like normal arithematic expression, leaving the case  of assignment operator, unary and ternary operator.
  1. Also note that in binary operators arithematic operators are of highest preference....... A for Arirthematic.
  2. Than follow relational operator...R for Relational operator(like < , > etc.)
  3. Than comes bitwise operator....B for Bitwise(eg...
  4. Than logical operator or Boolean operator...L....(eg. && etc)...
So learning way is MARBLE .
Notes:
Exception to MARBLE is bitwise shift operators which has higher precedence than Relational operators.
This can be noted by the fact that....>> has greater precedence than >.
Logical operator ! is of higher precedence being a unary operator.
Postfix is greater than prefix in precedence.
() is greater than [] in precedence...

C++
In case of C++, We have same precedence with some added operators.
1. :: operator is of higher precedence, with precedence = () operator.
2. 
const_cast  , dynamic_cast , reinterpret_cast ,  static_cast ,
typeid
+ we have:
 () Type cast, i.e. (type) expr
sizeof() Size in bytes
new Dynamically allocate storage
 new [] Dynamically allocate array
delete Dynamically free storage
delete [] Dynamically free array 


That's it.