Hacker Newsnew | comments | show | ask | jobs | submit login

Is there a reason C11 doesn't include typeof? It's been a gcc extension for decades now, and I see no reason it can't be part of the official standard.



My guess as someone who is not familiar with compiler internals is that the design of many compilers prevents them from implementing a typeof() operator without major changes to the way they analyze and store the parsed source code, so the standard writers decided not to include a feature that would not be widely implemented.

But, using _Generic(), one can do many of the things one would do with typeof(). For example, the max() example in [0] could probably be implemented using at most n^2 separate macros plus a _Generic() macro for each type, where n is the number of arithmetic types (though I think you'd still need GCC's statements within expressions in order to evaluate A and B only once).

I'm thinking something like this that combines the cbrt(X) example from the C1x spec [1] (ยง6.5.1.1 paragraph 5) with the gcc max() example, though I haven't tested it, and it could almost certainly be simplified by exploiting type promotion rules:

  #define max_ld_ld(A, B) ({long double _a = (A); \
      long double _b = (B); _a > _b ? _a : _b})
  
  #define maxld(A, B) _Generic((B), \
      long double: max_ld_ld, \
      int: max_ld_i, \
      /* etc. */ \
      )((A), (B))
  
  #define maxi(A, B) _Generic((B), \
      long double: max_i_ld, \
      int: max_i_i, \
      /* etc. */ \
      )((A), (B))
  
  #define max(A, B) _Generic((A), \
      long double: maxld, \
      int: maxi, \
      /* etc. */ \
      )((A), (B))
[0] http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

[1] http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

OT P.S. It is very annoying that Google has broken right-click+copy URL.

-----


The case of typeof has already been discussed for C99 and it has been rejected. In ISO C99 Rationale document (section 6.7.7), it is written: "A proposed typeof operator was rejected on the grounds of insufficient utility." Don't forget most of the work of the C committee is spent in resisting features suggestions.

-----




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: