Why can a comma be omitted in a printf () call?

I am using C # or Java.

How could the following statement be true in C?

printf("aaa" "bbb");

On my Xubuntu 15.04 with GCC 4.9. It outputs:

aaabbb

And as I tried, below also works!

 CHAR *p = "aaa""bbb""ccc"; printf(p); 

It outputs:

 aaabbbccc 

I think there should be a comma, but in this case the first line will be considered as a format string. So is this syntax legal?

+7
c
source share
5 answers

Yes, this is legal syntax due to translation phase 6 of ISO C99, # 5.1.1.2. Translation Phases:

  1. Associated string literal tokens are concatenated.
+16
source share

As mentioned, adjacent strings are concatenated by the compiler. But if you want to see some kind of difference, you can add a null delimiter \0 in your lines.

When adding aaa\0 your o / p will be just aaa , since printf will print until it finds the 1st \0 null delimiter.

 #include<stdio.h> int main() { printf("aaa\0" "bbb"); } 

Exit

aaa

+6
source share

Two lines are simply concatenated by the compiler.

+5
source share

When the compiler sees two consecutive string literals, it combines them (during parsing in the compiler), as you noticed. This will not work (compiler syntax error) for non-literals.

The comma operator is not concatenated. First, it evaluates the left operand, then the right and discards the result on the left, giving the correct result. It is useful for side effects (e.g. progn in Lisp,; in Ocaml, begin in the diagram). Of course, a comma is also used to separate arguments in calls.

+2
source share

As @Jens said, adjacent string literals are concatenated by the compiler.

One reason for this is that you can do preprocessors like this:

 #include <stdio.h> #if defined(__linux__) #define MY_OS "linux" #elif defined(_WIN32) #define MY_OS "windows" #else #define MY_OS "probably something BSD-derived" #endif int main(void){ printf("my os is " MY_OS "\n"); } 

Which saves a lot of time.

+1
source share

All Articles