How does c compare character variable against string?

The following code is completely ok in C

No, Not at all.

In your code

  if(ch=="a")

is essentially trying to compare the value of ch with the base address of the string literal "a",. This is meaning-and-use-less.

What you want here, is to use single quotes (') to denote a char literal, like

  if(ch == 'a')

NOTE 1:

To elaborate on the difference between single quotes for char literals and double quotes for string literal s,

For char literal, C11, chapter §6.4.4.4

An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in 'x'

and, for string literal, chapter §6.4.5

Acharacter string literal is a sequence of zero or more multibyte characters enclosed in
double-quotes, as in "xyz".


NOTE 2:

That said, as a note, the recommend signature of main() is int main(void).

Leave a Comment