How does c compare character variable against string?

前端 未结 3 781
北荒
北荒 2020-12-07 03:37

The following code is completely ok in C but not in C++. In following code if statement is always false. How C compares character variable against string?

3条回答
  •  醉梦人生
    2020-12-07 03:56

    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).

提交回复
热议问题