Name of function cannot be exactly same as of name of other function or identifier within the scope of the function.


(1) What will be output of following c program?


#include<stdio.h>
int main(){
   int number,val;
   number=5<<2+5>>2;
   val=++number;
   val=number(val);
   printf("%d",val);
   return 0;
}
int number(int val){
   val=~val;
  return val;
}

Output: Compilation error

Explanation: number is function name as well as name of variable in the same scope.

(2) What will be output of following c program?


#include<stdio.h>
int main(){
    int val;{
      int number;
      number=5<<2+5>>2;
      val=++number;
  }

  val=number(val);
  printf("%d",val);
  return 0;
}

int number(int val){
  val=~val;
  return val;
}

Output: -162
Explanation:
First consider following expression: 5 << 2 + 5 >> 2

In above express there are three operators. They are: <<, +, >>
Among three + operator enjoy highest precedence. Hence first of addition operation will perform.
=5 << (5 + 2) >> 2

Now in << and >>, both have equal precedence. Hence associative will decide will which operator will execute first. Associative of shifting is LEFT to RIGHT. Hence, in the expression left shifting operator will execute first. So
= (5 * 2 ^7) >> 2
= (5 * 128)>>2
Now right shifting operator will execute.
640 >> 2
= 640 /(2 ^2)
= 640/4
= 160
So number = 160
Since val = ++number
so val = 161
Now we are passing 161 as function parameter.
val= ~val  
It is equivalent to
val = -(val+1)
val = -(161+1)
Post a Comment