print % in c
Stan Brown
browns at iccgcc.decnet.ab.com
Wed Feb 27 03:07:26 AEST 1991
In article <1991Feb25.180600.5004 at ux1.cso.uiuc.edu>, gordon at osiris.cso.uiuc.edu (John Gordon) writes:
> To print special characters with printf(), precede the character
> with a \ character. Example:
>
> printf("This a percent sign: \%\n");
> printf("This is a backslash: \\\n");
The first of these is bad advice, and comes from mixing compile-time
treatment of strings with run-time treatment by printf( ) of its first
argument.
An easy counterexample:
printf("This is a number without percent sign: \%d\n", 1568);
will print:
This is a number without percent sign: 1568
And yes, I've tried it (Microsoft C 5.1).
Explanation:
The backslash in a string has special meaning at compile time, to tell
the compiler that the next character is special. The percent sign has
no special meaning at compile time.
So the two strings given above actually contain characters ending in
n, :, space, %, newline, ASCII 0
and h, :, space, \, newline, ASCII 0
The percent sign has special meaning at run time, in a printf string, to
introduce a conversion specification. The backslash has no special
meaning to printf. The standard states (page 135) that the complete
conversion specification to write a % shall be %%.
In the next paragraph on page 135, the standard states that if a
conversion specification is invalid, the behavior is undefined. Newline
is not a valid conversion specification. So a compiler is within its
rights to produce % from % followed by an invalid conversion
specification, but you can't count on it. (BTW Microsoft C 5.1 prints
nothing after the colon and space.)
Maybe this belongs in an FAQ? I haven't seen it often on the net,
but it seems a common misunderstanding among programmers.
My opinions are mine: I don't speak for any other person or company.
email: browns at iccgcc.decnet.ab.com
Stan Brown, Oak Road Systems, Cleveland, Ohio, USA +1 216 371 0043
More information about the Comp.lang.c
mailing list