简体   繁体   中英

string printed in reverse without reversing in the code

I tried to print the string by declaring it via ternary operator. Instead of any error it prints string in reverse.

Can someone explain please?

I was expecting string to be printed as even or odd based on the input.

 #include<stdio.h>

    void main()
    {
        int a;
        char *num;

        printf("Enter a number: ");
        scanf("%d", &a);

        num = (a % 2) ? 'odd' : 'even';

        printf("Its %s number", &num);

        getch();
    }

'odd' and 'even' are integer character constants.

According to the C Standard (6.4.4.4 Character constants)

10 An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (eg, 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

So in this call

printf("Its %s number", &num);

you are trying to output the address of the variable num as an address of a string that is you are trying to output a string but num does not point to a string.

You have to use string literals instead of the character constants.

What you mean is the following

    num = (a % 2) ? "odd" : "even";

    printf("Its %s number", num);

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