code.c这个代码可以打印下面所有函数输出,加深理解

01

image.png
image.png
image.pngimage.png
不声明时,编译器默认是有符号数。

02

image.png

03

int类型是32位,不能左移32位,在数字后加 L 将数字扩展为long型64位,就可以左移32位了。
image.png

Round up

  1. // NOTE: only works correctly if mult argument is exact power of two
  2. size_t roundup(size_t sz, size_t mult)
  3. {
  4. return (sz + mult-1) & ~(mult-1);
  5. }

image.png

size_t 这个类型的意义是什么?

前言:使用size_t可能会提高代码的可移植性、有效性或者可读性,或许同时提高这三者。
类型名称非常直观,它的含义就是“size type”,大小的类型,也直接意味着它是sizeof运算符结果的类型。
不同平台的size_t会用不同的类型实现,使用size_t而非int或unsigned可以写出扩展行更好的代码。

Absolute value

  1. int abs_val(int x)
  2. {
  3. int sn = x >> (sizeof(int)*CHAR_BIT -1);
  4. return (x ^ sn) - sn;
  5. }

(x + sn) ^ sn

Min

  1. int min(int x, int y)
  2. {
  3. int diff = x-y;
  4. return y + (diff & (diff>>31));
  5. }

image.png
Okay, we’re convinced it works for the ordinary cases, but what about at the extremes? Consider in what situations the subtraction can over􀃓ow beyond INT_MIN or INT_MAX . For what sort of values x and y does this happen? What happens at runtime when an integer operation overflows? Not sure? Try running the code to see. What is the result of the function in the case when the subtraction overflows?
另一个版本是

  1. int min(int x, int y)
  2. {
  3. return y ^ ((x ^ y) & -(x < y));
  4. }