1

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?

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
arup nath
  • 37
  • 1
  • 6

2 Answers2

3

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 :)

Lundin
  • 195,001
  • 40
  • 254
  • 396
1

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.

Mathieu D
  • 29
  • 5
  • 1
    What if the programmer doesn't know about every single one of the numerous, subtle, irrational type rules in C though? I'd dare say that most C programmers don't. – Lundin Feb 24 '17 at 11:06