3.61

function cread_alt should be

/*
 * cread-alt.c
 */
#include <stdio.h>
#include <assert.h>

long cread(long *xp) {
  return (xp ? *xp : 0);
}

long cread_alt(long *xp) {
  return (!xp ? 0 : *xp);
}

int main(int argc, char* argv[]) {
  long a = 0;
  assert(cread(&a) == cread_alt(&a));
  assert(cread(NULL) == cread_alt(NULL));
  return 0;
}


compile function cread in book sample and get

# long cread(long *xp)
# xp in %rdi
cread:
  movq (%rdi), %rax
  testq %rdi, %rdi
  movl $0, %edx
  cmove %rdx, %rax
  ret

the result of compiling cread_alt may be

# long cread_alt(long* xp)
# xp in %rdi
cread_alt:
  movl $0, %eax
  testq %rdi, %rdi
  cmovne (%rdi), %rax
comments powered by Disqus