Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 15 May 2020 07:02:33 +1000
From:      andrew clarke <mail@ozzmosis.com>
To:        Polytropon <freebsd@edvax.de>
Cc:        FreeBSD Questions <freebsd-questions@freebsd.org>
Subject:   Re: Multi-line text output via printf() et al.
Message-ID:  <20200514210233.sw6je2m3d6acnsib@ozzmosis.com>
In-Reply-To: <20200514220904.7a4c1e28.freebsd@edvax.de>
References:  <20200514220904.7a4c1e28.freebsd@edvax.de>

next in thread | previous in thread | raw e-mail | index | archive | help
On 2020-05-14 22:09:04, Polytropon (freebsd@edvax.de) wrote:

> c) multiple lines in one string:
> 
> 	printf("This is the first line of text.\n
> 	And this is the second line.\n
> 	Finally a third line.\n");

You need to add a line continuation backslash for this to work:

printf("This is the first line of text.\n \
And this is the second line.\n \
Finally a third line.\n");

> There is a specific restriction that if a string contains
> conversion specifications for variables, those have to be
> in the 1st argument, so printf() does not print several
> strings as individual arguments except there's a first
> one containing appropriate %s entries. This applies for
> any string containing %<something>: it has to be in the
> first argument passed to printf().
> 
> d) multiple strings with format string:
> 
> 	printf("%s%s%s",
> 		"This is the first line of text.\n",
> 		"And this is the second line.\n",
> 		"Finally a third line.\n");

There is the risk your program will crash here if you supply the wrong number
of arguments to printf(). It's easy to mess this up if you're not paying
attention to the parameter count, and if the printf() happens to be an error
message then the bug might not show up in production. Though linters built
into modern versions of gcc and clang will usually catch problems like this
and emit a warning.

> In this case, the \n could be in the format string instead
> of the text lines.
> 
> So, what's the correct (or at least recommended way) of
> doing this? Think about use cases like fprintf(stderr, ...)
> for things like usage messages, or printing to a file for
> multi-line entries.

I don't think it matters too much as long as you're consistent.

String internationalisation and localisation can complicate things though.

This:

printf(
  "This " "is " "a " "string.\n"
);

is uncommon in C code I suspect because not many people know it's allowed
by the preprocessor. In many (most?) other languages you need to
explicitly concat the strings together.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20200514210233.sw6je2m3d6acnsib>