Interview Questions
- How are arithmetic expressions evaluated?
- How are logical expression evaluated?
- Can a integer value be assigned to a char variable? What would be the result?
- Can a floating point value be assigned to a integer variable?
- Can a char variable be used in arithmetic expressions?
- What is the difference between preincrement and postincrement operators?
- What is Precedence?
- What is Associativity?
How are arithmetic expressions evaluated?
Result of an operation involving two integers is an integer. If atleast of the operands is a floating point number, result is a floating point number.
How are logical expression evaluated?
Expressions with && or || are evaluated left to right, and evaluation stops as soon as the truth or falsehood of the result is known. The precedence of && is higher than that of ||.
Can a integer value be assigned to a char variable? What would be the result?
Yes. If the value is too big to fit in a char, it will be truncated.
Can a floating point value be assigned to a integer variable?
Yes. The value will be truncated.
Can a char variable be used in arithmetic expressions?
A char is just a small integer, so chars may be freely used in arithmetic expressions.
What is the difference between preincrement and postincrement operators?
++n : Returns value of n and increments n
n++ : Increments n and returns the value ( So, returns the incremented value)
#include <stdio.h> int main() { int i=10,j=10; printf("i:%d\n",i++);//i:10 - actual value of i is returned printf("i:%d\n",i);//i:11 printf("j:%d\n",++j);//j:11 - incremented value of j is returned printf("j:%d\n",j);//j:11 }
What is Precedence?
Precedence decides which operation is executed first. * & / have priority than + and -. Consider example below:
#include <stdio.h> int main() { //* has higher precedence than + //Evaluated as 5 + (10 * 2) = 25. printf("i:%d\n", 5 + 10 * 2);//i:25 }
What is Associativity?
Associativity decide the order of execution when operators in an operation have higher priority.
Consider i = j = 5; Associativity of = operator is Right to Left. So, j=5 is executed first. And then i is assigned the result of earlier operation.
In the example below, associativity of * and / operators is Left to Right. So, evaluation is done similar to (5*2)/10. (If the execution was done like 5 * (2/10), result would be zero. Why??)
#include <stdio.h> int main() { printf("i:%d\n", 5 * 2 / 10);//1 }