groff
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

C Strings and String Literals. (Was: Pascal rides again)


From: Ralph Corderoy
Subject: C Strings and String Literals. (Was: Pascal rides again)
Date: Sun, 13 Nov 2022 20:08:58 +0000

Hi Branden,

> C doesn't _really_ have strings, except at the library level.
> It has character arrays and one grain of syntactic sugar for encoding
> "string literals", which should not have been called that because
> whether they get the null terminator is context-dependent.
>
>         char a[5] = "fooba";
>         char *b = "bazqux";
>
> I see some Internet sources claim that C is absolutely reliable about
> null-terminating such literals, but I can't agree.  The assignment to
> `b` above adds a null terminator, and the one to `a` does not.  This
> is the opposite of absolute reliability.  Since I foresee someone
> calling me a liar for saying that, I'll grant that if you carry a long
> enough list of exceptional cases for the syntax in your head, both are
> predictable.  But it's simply a land mine for the everyday programmer.

- C defines both string literals and strings at the language level,
  e.g. main()'s argv[] is defined to contain strings.

- In C, "foo" is a string literal.  That is the correct name as it is
  not a C string because a string literal may contain explicit NUL bytes
  within it which a string may not: "foo\0bar".

- A string literal has an implicit NUL added at its end thus "foo" fills
  four bytes.

- A character array may be initialised by a string literal.  Successive
  elements of the array are set to the string literal's characters,
  including the implicit NUL if there is room.

    char     two[2] = "foo";   // 'f' 'o'
    char   three[3] = "foo";   // 'f' 'o' 'o'
    char    four[4] = "foo";   // 'f' 'o' 'o' '\0'
    char    five[5] = "foo";   // 'f' 'o' 'o' '\0' '\0'
    char implicit[] = "foo";   // 'f' 'o' 'o' '\0'

That's it.

- The string literal is reliably terminating by a NUL.
- It is not context dependent whether a string literal has a terminating
  NUL.
- It is absolutely reliable and clearly stated in the C standard and in
  any other C reference worth its salt.
- There is no need to ‘carry a long enough list of exceptional cases for
  the syntax in your head’.
- An ‘everyday C programmer’ will know this simple behaviour by dint of
  being a C programmer who writes it every day; there is no landmine
  upon which to step.  :-)

Hope that helps clear up this corner of C.

-- 
Cheers, Ralph.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]