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