please explain how does the following C code work.
a) double ldexp(double x, int exponent) is a C math function
that returns x multiplied
by 2 raised to the power of exponent. How many narrowing and how
many promotions
happen automatically in the following code line? Name them one by
one and explain each
one separately.
float f = 2.2f * ldexp(24.4, 3.0 * 2) - 4.4;
b)
int function1(int num1, int num2) {
int num = num1 ^ num2;
int result = 0;
while(num > 0) {
result += (num & 1);
num >>= 1;
}
return result;
}
c)
int f1(unsigned int x) {
int count = 0;
while(x) {
count++; x = x&(x-1);
}
return count;
}
d)
int function2(unsigned int num) {
return num & ~(num - 1);
}
A)
At funciton call - ldexp(24.4, 30.0*2), 2 is converted to float results 2.0 (promotion) and 3.0 is multiplyed with 2.0 = 6.0 is conveted to int results 6 (narrowing) since exponent parameter is int and 24.4 (float) is converted to double(promotion) since x is double
then 2(int) is raised to the power of exponent(int) no conversion occurs, results int
at product of x and 2^6 - 2^6 converted to float (promotion)
again 2^6 converted to double(promotion) , since x is double
since return type is double , product of x (double) and 2^6(double) is returned no changes
after returned from funciton 2.2f is converted to double (promotion).
the 2.2(double) is multiplyed with return value of function (double) yields double
again 4.4 is converted to double (promotion), 4.4 is subtracted from the product of 2,2 and return value of function, finally yields double . it is conveted into float (narrowing).
for arthimetic operation all operands should be of same type (higher operand)type
Get Answers For Free
Most questions answered within 1 hours.