I came across a multi-line string while doing an inspection on a colleagues C code. I’ve never seen this sort of thing before, and didn’t know it was possible.
Something like this:
char* welcomeMessage = "Hello "
"Dale. "
"How are you?";
printf("%s", welcomeMessage);
will happily print out “Hello Dale. How are you?”.
It seems that you can define a string literal in C across multiple lines, without any need for a concatenation character (like ‘+’ in Java and C#).
I like that, even though I’ve been writing C for years now, I still occasionally come across little bits and pieces in the language that are new to me. And doing code inspections and reviews of other people’s code are a good way to share this sort of stuff and learn from each other.
I just happened to find this out on your site via Google 😉
Yes, I’m too used to other languages which you concatenate string with +
Thanks!
also found the link on google 😛
You could do something like that
char* welcomeMessage = “Hello \
Dale. \
How are you?”;
printf(“%s”, welcomeMessage);
Yeah, but Etienne, you can’t use backslashes while maintaining pretty (and arguably more readable) indentation.
Just stumbled across this on Google. I’d never seen this anywhere either; thanks for posting!
Indeed, happened to stumble across this while Googling. Seems to compile fine, hope it works in practice too! Thanks for the hint! *thumbsup*
// Mankku
Super! Works great in visual studio.
Stumbled across this. I’d be interested in knowing if you can write multiple lines to a file inside a single fprintf statement without using the \n command. For example, I have a bunch of text that needs to be sent verbatim to a file, but I don’t want to have to input fprintf(file,”line\nline\nline\n”); I’d rather do a command to the effect of:
fprintf(file,”
line
line
line
“);
Is there a way to do this? If so, I could simply copy and paste the file data into the code and it would write a file with the exact same data. Any ideas?
Thanks in advance.
Doug
Thank you for posting it. My code looks co much more prettier now! 🙂
Thanks for the Tip, it helped me with my Beginner Obj-C!
thanks for posting I too came across this whilst Googleing and as i had to write a report on it i researched a bit more, my time was limited but some further reading would be pointers and arrays, it seems that you have created one or the other using char* hope this helps
This will forever be immortalised by being #1 search result for c multi line strings, increasing readability of code for the infinite future. Thank you.
I also google searched, because I have 80 char requirement width for my source. Nice!
Instead of
char* welcomeMessage = “Hello ”
“Dale. ”
“How are you?”;
printf(“%s”, welcomeMessage);
In C you can just write:
printf(“Hello ”
“Dale. ”
“How are you?”);
Cheers.
Also found via Google search! Thanks a lot. New to C.