1

I have this:

char * str = "hahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohohohahahahahihihihihohohoho\0";

How do I format this correctly, breaking at 80 columns? Using:

char * str = "foo\
    bar";

seems to be a very bad idea, it leads to undefined behavior, making strlen() return nonsense values

edit: This is the undefined behavior I'm talking about:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *s = "haha\
               hihi\0";

    unsigned i = strlen(s);

    printf("Length: %i\n", i);

    return 0;
}

imperator@RomaAeterna ~/P/C/undefined> gcc -Wall -Wextra undefined.c 
imperator@RomaAeterna ~/P/C/undefined> ./a.out
Length: 14
  • 1
    That doesn't compile because you forgot the `=` in the second snippet. That aside, I fail to see the undefined behavior. – Blaze Mar 18 '19 at 12:40
  • Possible duplicate of https://stackoverflow.com/questions/797318/how-to-split-a-string-literal-across-multiple-lines-in-c-objective-c – Jose Mar 18 '19 at 12:42
  • @Blaze I compiled the second snippet (with = of course, thx) with `gcc -Wall -Wextra` and got no warning. The calculated string length was 10, instead of 6. That seems to be undefined behavior to me, though I suspect the compiler took the tab-indent as a number... – Theo Freeman Mar 18 '19 at 12:47
  • @TheoFreeman That's right, it adds the indentation on the next line to the string literal. Check out Bathsheba's answer for a much better solution. – Blaze Mar 18 '19 at 12:50
  • @Blaze It seems the suggested first solution in Jose's link is flawed then – Theo Freeman Mar 18 '19 at 12:54
  • 1
    @TheoFreeman to be fair, that solution includes the better solution also explains that the whitespace if part of the problem. One thing to note is that the context of that answer is an SQL query, so the extra whitespace isn't a big issue. – Blaze Mar 18 '19 at 13:00

2 Answers2

5

You can use multiple lines like this:

char* str = "line1"
            "line2"
            "line3";

for example. Think of "" as being a compile-time concatenation operator; in fact, any whitespace between the closing " of one string and the opening " of the next will suffice.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
-2

Best idea is use preprocesor to this, because this not use memory (has matter in embedded):

#define TEXT "jfsdkfnkd jfsn kjdsjkdsf ndjkksnfjkdsnf njdsjkfdnfkjdsfnd\
dkf dfhfhjfbdsfhjbffjsbdhfds"
strlen(TEXT);
Igor Galczak
  • 142
  • 6