简体   繁体   中英

C - Macro detects wrong datatypes

I'm trying to define a macro that prints any datatype correctly but it appears to detect what type I'm passing incorrectly. Why?

Code: (I've left out the includes but they're there.)

void print_int(int x) { printf("PRINTING INT: %d", x); }
void print_float(float x) { printf("%.3f", x); }
void print_char(char x) { printf("%c", x); }
void print_string(char *x) { printf("%s", x); }
void print_bool(bool x) { printf("%s", x ? "true" : "false"); }

#define print(X) \
    _Generic((X),\
        int: print_int, \
        float: print_float, \
        double: print_float, \
        char: print_char, \
        char *: print_string, \
        bool: print_bool)(X)

int main(void) {
    
    printf("\n\nprint string: ");
    print("Hello there!"); // prints as string

    printf("\nprint int: ");
    print(3); // prints as int

    printf("\nprint float: ");
    print(4.55); // prints as float

    printf("\nprint bool: ");
    print(false); // prints as bool

    printf("\nprint char: ");
    print('A'); // prints as char

    return 0;
}

Actual output:

print string: Hello there!
print int: PRINTING INT: 3
print float: 4.550
print bool: PRINTING INT: 0
print char: PRINTING INT: 65

Correct output:

print string: Hello there!
print int: PRINTING INT: 3
print float: 4.550
print bool: false
print char: A

I'd love to know where this is going wrong, because I have no clue.

In this call

print('A');

the argument is an integer character constant.

Integer character constants in C (opposite to C++ where they are named character literals) have the type int instead of the type char .

From the C Standard (6.4.4.4 Character constants)

10 An integer character constant has type int .

Here is a demonstrative program that shows this peculiarity of C.

#include <stdio.h>

int main(void) 
{
    printf( "suzeof( 'A' ) = %zu\n", sizeof( 'A' ) );
    
    char c = 'A';
    
    printf( "suzeof( c ) = %zu\n", sizeof( c ) );

    return 0;
}

The program output is

suzeof( 'A' ) = 4
suzeof( c ) = 1

If you want to get the expected by you result then write

print( (char )'A' );

or

char c = 'A';
print( c );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM