c/c++ question: comparing/sorting sctructs

Discussion of chess software programming and technical issues.

Moderator: Ras

User avatar
sje
Posts: 4675
Joined: Mon Mar 13, 2006 7:43 pm

Another problem with memcmp()

Post by sje »

In C/C++ a logically true value from the viewpoint of an if, while, do, or relational is any nonzero value. These non-zero values can be stored in a C/C++ struct/class where they may be the same from the view of logical tests but not from the view of memcmp().

Relational testing on a component basis is the only safe and portable way of comparing structured objects.
Sven
Posts: 4052
Joined: Thu May 15, 2008 9:57 pm
Location: Berlin, Germany
Full name: Sven Schüle

Re: Another problem with memcmp()

Post by Sven »

sje wrote:In C/C++ a logically true value from the viewpoint of an if, while, do, or relational is any nonzero value. These non-zero values can be stored in a C/C++ struct/class where they may be the same from the view of logical tests but not from the view of memcmp().

Relational testing on a component basis is the only safe and portable way of comparing structured objects.
Although I understand your intention, and also strongly recommend to avoid using memcmp() for struct comparison, I think that _this_ example is not fully convincing. If a struct member has an integer-like data type (int, short, long, ...) then I would expect that a struct comparison uses the numerical values, so there would be more than just "zero or non-zero". If the intention is to store a logical value in a struct than you would use a bool, and in this case even memcmp() would work since there are only two numerical representations of a bool (0 and 1).

Of course people do such things frequently, storing an int but later only evaluating it like a bool. I just say that it _should_ be done differently.

Sven