-1

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();
    }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 6
    E.g. `'odd'` is not a string. It's a multi-***character*** literal. `"odd"` is a string. C is not Python or Javascript, single quotes are for single characters, double quotes for strings. – Some programmer dude Aug 13 '19 at 10:25
  • 4
    `num = (a % 2) ? 'odd' : 'even';` - you're compiler *didn't* warn you about multi-character literals? That should be `num = (a % 2) ? "odd" : "even";` . Further, `num` *should* be `const char*` , and the final print should be. `printf("Its %s number", num);` - I suggest you rewind a few chapters in whatever text you're studying. – WhozCraig Aug 13 '19 at 10:26
  • 1
    Moreover the standard definition of `main` here should be `int main(void)`, and, function `getch()` is not a standard C function in `stdio.h`. It's a non-standard library function possibly in Windows `conio.h` or old Turbo C. Please pay attention to compiler warnings. – Weather Vane Aug 13 '19 at 10:54
  • 1
    You're supposed to get *diagnostics messages* from your compiler for this. – Antti Haapala -- Слава Україні Aug 13 '19 at 10:58

1 Answers1

1

'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 (e.g., '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);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335