Search code examples
cgccgcc-warning

Why is my output wrong? C newbie


#include <stdio.h>
int main(void) 
{
    char username;
    username = '10A';
    printf("%c\n", username);
    return 0;
}

I just started learning C, and here is my first problem. Why is this program giving me 2 warnings (multi-character constant, overflow in implicit constant conversion)?

And instead of giving 10A as output, it is giving just A.


Solution

  • You are trying to stuff multiple characters into a single set of '', and into a single char variable. You need "" for string literals, and you'll need an array of characters to hold a string. And to print a string, use %s.

    Putting all of this together, you get:

    #include <stdio.h>
    int main(void) 
    {
        char username[] = "10A";
        printf("%s\n", username);
        return 0;
    }
    

    Footnote

    From Jonathan Leffler in the comments below regarding multi-character constants:

    Note that multi-character constants are a part of C (hence the warning, not an error), but the value of a multi-character constant is implementation defined and hence not portable. It is an integer value; it is larger than fits in a char, so you get that warning. You could have gotten almost anything as the output — 1, A and a null byte could all be plausible.