Reputation: 43
int friends = 20;
printf("I have %d friend%c", friends , (friends !=1 ? "s" : ""));
return 0;
So whenever I run the code it debugs into this
I have 20 friend$
It works fine when I run it with %s format specifier after the friend
. s
is only one character so why doesn't it work?
Upvotes: 0
Views: 311
Reputation: 81
"s" is not a one character, its a String Literal whose type is char *
's' is one character Constant whose type is int.
String Literal in C requires double quotes, and printf( ) have format specifier %s to print string literals.
Character Constant in C requires single quotes, and printf( ) have format specifier %c to print them.
Now your code snippet,
printf("I have %d friend%c", friends , (friends != 1 ? "s" : ""));
will return string literal, since
"s" or " "
is string literal and printf( ) requires format specifies "%s" to print them.
if you want to use %c format specifier in code snippet, then use, character constant 's' instead of string literal "s"
printf("I have %d friend%c", friends , (friends != 1 ? 's' : ' '));
^
Also note that, there must be a space between single quotes as show above the caret symbol otherwise it would give error: empty character constant.
In case of string literals, empty string is allowed.
Upvotes: 1
Reputation: 11921
so why doesn't it work? because %c
expects char
but expression (friends !=1 ? "s" : "")
results in strings(double quotes). So either use %s
like
printf("I have %d friend%s", friends , (friends !=1 ? "s" : ""));
Or
Replace "s"
with 's'
and ""
with ' '
as %c
expects char
.
printf("I have %d friend%c", friends , (friends !=1 ? 's' : ' '));
Upvotes: 3