Is there any Identical operator === in C like that in PHP?

筅森魡賤 提交于 2019-12-23 02:53:19

问题


In PHP, the Identical Operatpr (===), returns TRUE if both sides are exactly equal, and they are of the same type.

Is there any similar thing in C world?


回答1:


With C11 _Generic available, your question made me want to invent one.

Basically you can implement this with a macro such as this:

#define is_truly_equal(a, b) \
  _Generic((a), \
           int:    _Generic((b), int: (a) == (b),   default: 0), \
           short:  _Generic((b), short: (a) == (b), default: 0), \
           default 0:)

Which can get turned into an easy-to-maintain, hard-to-read X macro list:

#define TYPE_LIST(a,b)  \
  X(a,b,int)            \
  X(a,b,unsigned int)   \
  X(a,b,short)          \
  X(a,b,unsigned short) \
  X(a,b,char)           \
  X(a,b,signed char)    \
  X(a,b,unsigned char)  \
  X(a,b,float)          \
  X(a,b,double)

#define X(a,b,type) type: _Generic((b), type: (a) == (b), default: 0),
#define is_truly_equal(a, b) _Generic((a), TYPE_LIST(a,b) default: 0)

Working example:

#include <stdio.h>

#define TYPE_LIST(a,b)  \
  X(a,b,int)            \
  X(a,b,unsigned int)   \
  X(a,b,short)          \
  X(a,b,unsigned short) \
  X(a,b,char)           \
  X(a,b,signed char)    \
  X(a,b,unsigned char)  \
  X(a,b,float)          \
  X(a,b,double)

#define X(a,b,type) type: _Generic((b), type: (a) == (b), default: 0),
#define is_truly_equal(a, b) _Generic((a), TYPE_LIST(a,b) default: 0)

inline void print_equal (_Bool is_equal)
{
  is_equal ? 
  printf("equal:     ") : 
  printf("not equal: ");
}

#define print_expr(p1, p2) print_equal( is_truly_equal(p1, p2) ); printf(#p1 ", " #p2 "\n")

int main (void)
{
  print_expr(1,1);
  print_expr(1,2);
  print_expr(1,1u);
  print_expr(1, (short)1);

  print_expr((signed char)'A',   (char)'A');
  print_expr((unsigned char)'A', (char)'A');
  print_expr('A', 65);
  print_expr('A',  (char)'A');
  print_expr('A', +(char)'A');
}

Output

equal:     1, 1
not equal: 1, 2
not equal: 1, 1u
not equal: 1, (short)1
not equal: (signed char)'A', (char)'A'
not equal: (unsigned char)'A', (char)'A'
equal:     'A', 65
not equal: 'A', (char)'A'
equal:     'A', +(char)'A'

Excellent way to experiment with (and cringe over) the C language type system :)




回答2:


I don't see why you should need to use a function like this in C or java, it is the programer's job to only compare same type variables, as you have to explicitly declare them.



来源:https://stackoverflow.com/questions/42434485/is-there-any-identical-operator-in-c-like-that-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!