Skip to content
Browse files

sys/util.h: helper macro to perform pointer difference

Some code casts pointers to ints in order to obtain their difference.
The compiler complains on 64-bit targets as an int is not wide enough
to hold a pointer.

Let's introduce the PTR_DIFF() helper macro to applies the proper cast
to pointers before performing a difference on them, and still return the
result as an int which should be large enough in practice.

Signed-off-by: Nicolas Pitre <>
  • Loading branch information...
Nicolas Pitre authored and andrewboie committed Jul 9, 2019
1 parent f8908cd commit 755cc644cc0b47dfa335219cc305a04a14e4ec25
Showing with 3 additions and 0 deletions.
  1. +3 −0 include/sys/util.h
@@ -25,6 +25,9 @@
#define POINTER_TO_INT(x) ((intptr_t) (x))
#define INT_TO_POINTER(x) ((void *) (intptr_t) (x))

/* Helper to get the difference between two pointers as an int */
#define PTR_DIFF(y, x) ((int)((intptr_t)(y) - (intptr_t)(x)))

#if !(defined (__CHAR_BIT__) && defined (__SIZEOF_LONG__))
# error Missing required predefined macros for BITS_PER_LONG calculation

0 comments on commit 755cc64

Please sign in to comment.
You can’t perform that action at this time.