I was trying to understand some code and came across a string
literal definition as:
char a[]="abc""def"; // string-1
I had seen eariler only string literal with characters in a single
pair of quotes(") e.g.
char a[]="abcdef"; // string-2
Please clear why string-1 is not showing syntax error and how it is
same as string-2.
Thanks,
The preprocessor will concatenate them.
--
Ian Collins
Because string literals are concatenated before syntactic and
semantic analysis.
> The preprocessor will concatenate them.
Nit: The compiler will concatenate them. Preprocessors are
usually limited to translation phases 1 through 4. String
concatenation is translation phase 6 [cf 5.1.1.2.]
--
Peter
And the reason for this apparently pointless thing is that it lets you
construct string literals at compile time:
#define NAME "Nick"
char a[] = "Hello " NAME " and welcome"
Combined with the "stringizing" feature and you can can do even more.
--
Online waterways route planner | http://canalplan.eu
Plan trips, see photos, check facilities | http://canalplan.org.uk
and break up long strings over multiple lines
You forgot about:
char foo[] = "This represents a"
" long string, which"
" won't fit on a"
" single line.";
or
char foo[] = "This is line 1.\n"
"And this is another line.";
--
Kenneth Brody
> On 4/20/2010 2:42 AM, Nick wrote:
>> Peter Nilsson<ai...@acay.com.au> writes:
>>
>>> Ian Collins<ian-n...@hotmail.com> wrote:
>>>>> I was trying to understand some code and came across a
>>>>> string literal definition as:
>>>>> char a[]="abc""def"; // string-1
> [...]
>> And the reason for this apparently pointless thing is that it lets you
>> construct string literals at compile time:
>>
>> #define NAME "Nick"
>> char a[] = "Hello " NAME " and welcome"
>>
>> Combined with the "stringizing" feature and you can can do even more.
>
> You forgot about:
>
> char foo[] = "This represents a"
> " long string, which"
> " won't fit on a"
> " single line.";
I did indeed
> or
> char foo[] = "This is line 1.\n"
> "And this is another line.";
Which is a huge improvement over:
char foo[] = "This is line 1.
And this is another line.";
Did C ever allow this. I've a hazy feeling some versions might have.
No C standard ever allowed this, but I think many pre-ANSI compilers
did.
You could also write:
char foo[] = "This is line 1.\n\
And this is another line.";
But that's also quite ugly. Apart from depending critically on the
indentation of the second line (something that's easy to mess up while
maintaining the code), it can become a syntax error if there's any
whitespace after the \.
--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"