C language "all-around comparison function" (second edition), any data type

Source: Internet
Author: User

First version:
[Cpp]
# Include <stdio. h>
 
// The following is the all-round comparison function. a> B returns an integer. a <B returns a negative number. a = B returns 0.
# Define COMPARE (TYPE, a, B) (TYPE) a-(TYPE) B)
 
Int main (int argc, char * argv [])
{
Double a = 1, B = 1.5, c;
Int x = 10, y = 1, z;
Char m = 'M', n = 'n', k;

C = COMPARE (double, a, B );
Printf ("% lf \ n", c );

Z = COMPARE (int, x, y );
Printf ("% d \ n", z );

K = COMPARE (char, m, n );
Printf ("% d \ n", k );

Return 0;
}

The returned data types are inconsistent, which is related to the input data type. Can we return the int type results uniformly?


Version 2: The comparison result is of the int type.

[Cpp]
# Include <stdio. h>
 
// The following is the all-round comparison function. a> B returns an integer. a <B returns a negative number. a = B returns 0.
# Define COMPARE (TYPE, a, B) (TYPE) a-(TYPE) B) = 0? 0 :( (TYPE) a-(TYPE) B)> 0? 1:-1 ))
 
Int main (int argc, char * argv [])
{
Int result;
Double a = 1, B = 1.5;
Int x = 10, y = 1;
Char m = 'M', n = 'n ';
Float f1 = 6.02, f2 = 6.0200002;

Result = COMPARE (double, a, B );
Printf ("% d \ n", result );

Result = COMPARE (int, x, y );
Printf ("% d \ n", result );

Result = COMPARE (char, m, n );
Printf ("% d \ n", result );

Result = COMPARE (float, f1, f2 );
Printf ("% d \ n", result );

Return 0;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.