2

wrote this code to "find if the given character is a digit or not"

#include<stdio.h>
int main()
{
    char ch;
    printf("enter a character");
    scanf("%c", &ch);
    printf("%c", ch>='0'&&ch<='9');
    return 0;
}

this got compiled, but after taking the input it didn't give any output. However, on changing the %c in the second last line to %d format specifier it indeed worked. I'm a bit confused as in why %d worked but %c didn't though the variable is of character datatype.

6
  • @MitchWheat I don't understand, sorry, I'm basically just starting with C. Jul 11, 2022 at 7:52
  • @Lundin Oops ... need more coffee. I'll defer posting an answer, as you can probably do better than I would. Jul 11, 2022 at 7:59
  • @AdrianMole Well I guess I have to, now that I reopened it... :)
    – Lundin
    Jul 11, 2022 at 8:01
  • 3
    ch>='0'&&ch<='9' evaluates to 0 or 1 neither of which are printable characters. Jul 11, 2022 at 8:01

2 Answers 2

5

Characters in C are really just numbers in a token table. The %c is mainly there to do the translation between the alphanumeric token table that humans like to read/write and the raw binary that the C program uses internally.

The expression ch>='0'&&ch<='9' evaluates to 1 or 0 which is a raw binary integer of type int (it would be type bool in C++). If you attempt to print that one with %c, you'll get the symbol table character with index 0 or 1, which isn't even a printable character (0-31 aren't printable). So you print a non-printable character... either you'll see nothing or you'll see some strange symbols.

Instead you need to use %d for printing an integer, then printf will do the correct conversion to the printable symbols '1' and '0'


As a side-note, make it a habit to always end your (sequence of) printf statements with \n since that "flushes the output buffer" = actually prints to the screen, on many systems. See Why does printf not flush after the call unless a newline is in the format string? for details

1
  • Yep, got it! Thanks for clearing the doubt and the tip! Jul 11, 2022 at 8:11
1

In a memory, int take 4 bytes of memory you are trying to storing the int values in a character which will return the ascii value not a int value in %c if you are using a %d which will return the int value which are storing in a memory of 4 bytes memory.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.