0

Is there a cross-platform way to determine whether ptrdiff_t is the same as long or long long during preprocessing?

I know __PTRDIFF_TYPE__ should give the type with gcc/g++, but it doesn't seem to be defined in VC/VC++ for Windows. Is there a better approach than the following?

#ifndef __PTRDIFF_TYPE__
# if _WIN64
#  define __PTRDIFF_TYPE__ long long
# else
#  define __PTRDIFF_TYPE__ long
# endif
#endif

If not possible during preprocessing, is there a compile time approach? I'm looking for a non-C++11 solution, but if you've got a really nice modern solution, feel free to share!

Alec
  • 583
  • 3
  • 21
  • Why do you need to know? The point of defining `ptrdiff_t` in the standard library is that you don't have to care how it's defined. – Keith Thompson Dec 22 '15 at 03:49
  • I'm trying to convert a Python2 `PyIntObject` to a `ptrdiff_t`, and there are different methods to convert it to `long` and to `long long`. I suppose technically the long long approach would always work, but it's not as clean since Python internally stores the value in a long. – Alec Dec 22 '15 at 12:16
  • 1
    Please add that information to the question. You have an [XY problem](http://meta.stackexchange.com/q/66377/167210). You need to convert a `PyIntObject` to a `ptrdiff_t` but rather than asking about that, you're asking how to determine which type is used for `ptrdiff_t`. (BTW, `ptrdiff_t` isn't necessarily either `long` or `long long`, but it's likely to be one or the other on any platform that supports Python.) – Keith Thompson Dec 22 '15 at 18:53

1 Answers1

2

A compile-time approach is very obvious:

if (sizeof(ptrdiff_t) == sizeof(long))

or

if (sizeof(ptrdiff_t) == sizeof(long long))

TMK, there are no portable defines for this. However, this is just a minor obstacle. With just a little bit of scripting, any compile-time test of this nature can be trivially converted to, essentially, a preprocessor-based test, using standard tools like autoconf and automake. These are standard tools used by thousands of free software libraries and tools, for this precise purpose.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • On some implementations, `long` and `long long` are the same size (but they're still distinct types). – Keith Thompson Dec 22 '15 at 03:50
  • This would merit another sizeof(long) == sizeof(long long) test, that's all. – Sam Varshavchik Dec 22 '15 at 12:00
  • If `sizeof(long) == sizeof(long long)`, you can't easily tell which of them is used to define `size_t`. Whether that's a problem friends on what the OP is doing (which is a bit clearer with the latest comment). – Keith Thompson Dec 22 '15 at 16:34