Comparing two functions in C

int r2 (int a, int b)
{
return (a + (1<<(b-1))) >>b;
}

int r3 (int a, int b)
{
 return (a + (1<<(b-1)) -1 -(a>>31)) >>b;
}
  • What is the difference between the two?
  • What could be the advantage of using additional operations in this way in the r3 () function?

This question was asked in an interview with me. I could easily expand the expressions, but I did not get the answer to the second question.

+4
source share
3 answers

It appears that these functions are trying to provide rounding rather than truncation to divide a positive number a by 2 by a power of b. If you expand these functions for the interviewer, I’m sure that you explained 2 things to him.

(, , , , , .)
, , *.5 , , 3 :

a = 13, b = 3: r2 = > 2, r3 = > 2: 13/2 ^ 3 = 1.625
a = 12, b = 3: r2 = > 2, r3 = > 1:12/2 ^ 3 = 1,5
a = 11, b = 3: r2 = > 1, r3 = > 1:11/2 ^ 3 = 1.375

( , , , . , " c skilz" .)

+1

- . a / pow(2,b), .

, , a / pow(2,b) . , .

, (1<<(b-1)) / pow(2,b) 0,5, floor((a+0.5) / pow(2,b)).

, a>>31 0 a -1 a ( 32- int s). a, -1 + (a>>31) == 0, , , .. . a, -1 + (a>>31) == -1, , .

+3

1. ?

-2 ( UB, b ). r2 . r3 0.

2. , r3()?

r3 , int. int 0.

Note. With the advent of 64-bit int, as well as the growth of embedded processors using 16-bit int, hard coding 31is a dubious coding. Instead a>>31, use something like a>>(sizeof(int) *CHAR_BIT - 1).

For me, this was the first thing that stood out. He made the opportunity , possibly knowing the company’s market, to show how this narrow view of C could negatively affect the company.
Look not only at the question. Consider the applicability of the question.

+1
source

All Articles