Difference between \% and %% [duplicate] - c

This question already has answers here:
Why is percentage character not escaped with backslash in C?
(4 answers)
How to escape the % (percent) sign in C's printf
(13 answers)
Closed 9 years ago.
After reading over some K&R C I saw that printf can "recognize %% for itself" I tested this and it printed out "%", I then tried "\%" which also printed "%".
So, is there any difference?
Edit for code request:
#include <stdio.h>
int main()
{
printf("%%\n");
printf("\%\n");
return 0;
}
Output:
%
%
Compiled with GCC using -o
GCC version: gcc (SUSE Linux) 4.8.1 20130909 [gcc-4_8-branch revision 202388]

%% is not a C escape sequence, but a printf formatter acting like an escape for its own special character.
\% is illegal because it has the syntax of a C escape sequence, but no defined meaning. Escape sequences besides the few listed as standard are compiler-specific. In all likelihood the compiler ignored the backslash, and printf did not see any backslash at runtime. If it had, it would have printed the backslash in the output, because backslash is not special to printf.

Both are not the same. The second one will print %, but in case of the first one, you will get compiler warning:
[Warning] unknown escape sequence: '%' [enabled by default]
The warning is self explanatory that there is no escape sequence like \% in C.
6.4.4.4 Character constants;
says
The double-quote " and question-mark ? are representable either by themselves or by the escape sequences \" and \?, respectively, but the single-quote ' and the backslash \ shall be represented, respectively, by the escape sequences \' and \\.
It is clear that % can't be represented as \%. There isn't any \% in C.

When "%%" is passed to printf it will print % to standard output, but "\%" in not an valid escape sequence in C. Hence the program will compile, but it will not print anything and will generate a warning:
warning: spurious trailing ‘%’ in format [-Wformat=] printf("%");
The list of escape sequences in C can be found in Escape sequences in C.
This won't print % for the second printf.
int main()
{
printf("%%\n");
printf("\%");
printf("\n");
return 0;
}
Output:
%

Related

Warning: unknown escape sequence: '\040', why not '\x20'? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
When I compile a C file has contents below:
#include <stdio.h>
#define FILE_NAME "text\ 1"
int main()
{
FILE* file_ptr = fopen(FILE_NAME, "w");
fclose(file_ptr);
return 0;
}
get warning:
tt.c: In function ‘main’:
tt.c:6:37: warning: unknown escape sequence: '\040'
6 | FILE* file_ptr = fopen(FILE_NAME, "w");
|
I know it caused by \ in a string of my C language code and 40 is decimal 32 as ASCII of SPACE. Why the warning is '\040' not '\x20'?
And seems also in bash \ transfer to \040 seed to binaries (not sure).
Is there a rule to force it?
Update:delete '\32' which used to represent ASCII of SPACE to decimal.
How I encounter this problem?
I just wanna know how Bash process ESCAPED SPACE, I thougt bash turn it to SPACE, but after I check source code of Bash (hard for me). I found maybe Bash treat \ as normal string of characters as below source code not involved \ :
#define slashify_in_quotes "\\`$\"\n"
#define slashify_in_here_document "\\`$"
#define shell_meta_chars "()<>;&|"
#define shell_break_chars "()<>;&| \t\n"
#define shell_quote_chars "\"`'"
So I think Bash turn the \ to the command or binary to process, so I write above simple C file to check how C treat \
So my question is Why gcc warning '\040' not '\x20'?
For how Bash treat \ still need me to check...
Answer to Updated Question
Why the warning is '\040' not '\x20'?
This is merely a choice by the compiler implementors. When you have \ in a string or character constant followed by something that is not a recognized escape sequence, the compiler warns you. For example, if you had \g, the compiler would warn you that \g is not recognized. When the character after the \ may be unclear, because it is a white space character that cannot be distinguished from others (like space from tab) or is not a printable character, the compiler shows it by value in the error message. This helps you find the exact character in your text editor, in case some unprintable character has slipped into the source code. The compiler authors could have used hexadecimal but simply chose to use octal.
I will fault them for using an inconsistent style. In GCC 10.2, \g results in the message unknown escape sequence: '\g', but \ results in the message unknown escape sequence: '\040'. These should either be:
unknown escape sequence: 'g' and unknown escape sequence: '\040' or
unknown escape sequence: '\g' and unknown escape sequence: '\\040'.
Answer to Original Vague Question
C 2018 6.4.4.4 specific character constants in C source code, and paragraph 1 lists four choices for escape-sequence: simple-escape-sequence, octal-escape-sequence, hexdecimal-escape-sequence, and univesal-char-name.
An octal-escape-sequence is \ followed by one to three octal digits. Thus, \040 the character with code 0408 = 32, and \32 is the character with code 328 = 26.
There is no decimal escape sequence; \32 is an octal escape sequence, not decimal. (Also note that because octal escape sequences can have various lengths, if one wishes to follow it by an octal digit, one must use all three allowed digits. \324 will be parsed as one character, not as \32 followed by 4, whereas \0324 is \032 followed by 4.)
A hexadecimal-escape-sequence is \x followed by any positive integer number of hexadecimal digits. \x20 is equal to \040.
(A simple-escape-sequence is one of \', \", \?, \\, \a, \b, \f, \n, \r, \t, or \v. A universal-character-name is \u followed by four hexadecimal digits or \U followed by eight hexadecimal digits.)

\\\ prints just one backslash?

In C, on mentioning three backslashes, like so:
#include <stdio.h>
int main() {
printf(" \\\ ");
}
prints out just one backslash in the output. Why and how does this work?
That sequence is:
A space
A double backslash, which encodes a single backslash in the runtime string
A backslash followed by a space, which is not a standard escape sequence and should give you a diagnostic
The C11 draft says (in note 77):
The semantics of these characters were discussed in 5.2.2. If any other
character follows a backslash, the result is not a token and a diagnostic is
required.
On godbolt.org I got:
<source>:8:14: warning: unknown escape sequence '\ ' [-Wunknown-escape-sequence]
So you seem to be using a non-conforming compiler, which chooses to implement undefined backslash sequences by just letting the character through.
That is printing:
space
slash
escaped space
The 3rd slash is being interpreted as "slash space"
C11; 6.4.4.4 Character constants:
The double-quote " and question-mark ? are representable either by themselves or by the
escape sequences \" and \?, respectively, but the single-quote ' and the backslash \
shall be represented, respectively, by the escape sequences \' and \\.
So, To represent a single backslash, it’s necessary to place double backslashes \\ in the source code. To print two \\ you need four backslash \\\\. In your code extra \ is a space character, which isn't valid.
It is indeed a very simple operation in c. A \ is just a escape sequences. Hence below statement will print two slash.
printf(" \\\\ ");
For example some characters in c are represented with a slash like end of a line character \n or end of a string character \0 etc. But if you want to print such a character as it is what will you do? Hence you need to add a escape sequence character in front of it:
printf("\\n"); // will print \n
But
printf("\n"); // will print end of character hence you don't see anything in output

Why does printf("%%") print only one percent (%) symbol? [duplicate]

This question already has answers here:
How to escape the % (percent) sign in C's printf
(13 answers)
Closed 8 years ago.
When I run this following code:
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
printf("%%");
getch();
}
I get % as an output?
What might be the reason behind this logic?
That is what printf does: it is print formatted (f for formatted). It uses % as the formatting character. It is the only reserved character and needs to be escaped to represent it self, i.e. %%. See the manual for more information on formatting: printf.
P.S.: Never use a string that is not a part of the program as the first argument. To print a string message that was input by a user, do printf(%s, message);. Otherwise you will have a security hole in your code.
% comes into format specifiers.
Example
When we write printf("%d", 20);, it will print 20 rather than %d. because the compiler treats % as a format specifier. In the mind of the compiler, the meaning of % is somewhat special.
So if you want that "%" should be the output, then you must write printf("%%"). Here the first % sign will suppress the meaning of the % format specifier and will print % as an output.
From the standard ISO/IEC 9899:1999 (E)
7.19.6.1
Each conversion specification is introduced by the character %.
The conversion specifiers and their meanings are:
% - A % character is written. No argument is converted. The complete
conversion specification shall be %%.
For C printf, % is a special character which typically indicates a parameter to substitute at that position: printf("Hello, %s\n", "World!"); results in "Hello, World!". There are lots of different things you can put after the % depending on the data you want to output. So that leaves the problem of "What if I want to print a percent symbol"?
The solution: Use %%.
The same is true of the special escape character \. "\n" means to print a new line. If you want to actually print the forward slash, you have to put it twice \\
See Printf format string and MSDN.

Compilation Error in C-File handling

#include<stdio.h>
#include<conio.h>
FILE *fp;
int main()
{
int val;
char line[80];
fp=fopen("\Users\P\Desktop\Java\a.txt","rt");
while( fgets(line,80,fp)!=NULL )
{
sscanf(line,"%d",&val);
printf("val is:: %d",val);
}
fclose(fp);
return 0;
}
Why is there a compile error in the line fp=fopen("\Users\P\Desktop\Java\a.txt","rt")?
Escape your backslashes.
fp=fopen("\\Users\\P\\Desktop\\Java\\a.txt","rt");
xx.c:8:12: error: \u used with no following hex digits
fp=fopen("\Users\P\Desktop\Java\a.txt","rt");
^
xx.c:8:12: warning: unknown escape sequence '\P'
xx.c:8:12: warning: unknown escape sequence '\D'
xx.c:8:12: warning: unknown escape sequence '\J'
The issue with the backslash. Backslash is an escape in a C char string.
Try this
fp=fopen("\\Users\\P\Desktop\\Java\\a.txt","rt");
or this depending on your OS:
fp=fopen("/Users/P/Desktop/Java/a.txt","rt");
You may be familiar with how "\n" (newline) and "\t" (tab) are used in C-strings.
The compiler will look at any \<Character> and try to interpret it as an Escape-Sequence.
So, where you wrote "\Users\P\Desktop\Java\a.txt", the compiler is trying to treat
\U, \P, \D, \J and \a as special escape-sequences.
(The only one that seems to be valid is \a, which is the Bell/Beep sequence. The others should all generate errors)
As others have said, use \\ to insert a literal Backslash character, and not start an escape sequence.
P.S. Shame on you for not including the the compiler message in your question.
The worst questions all say, "I got an error", without ever describing what the error was.

How do I print the percent sign(%) in C? [duplicate]

This question already has answers here:
How to escape the % (percent) sign in C's printf
(13 answers)
Closed 7 years ago.
Why doesn't this program print the % sign?
#include <stdio.h>
main()
{
printf("%");
getch();
}
Your problem is that you have to change:
printf("%");
to
printf("%%");
Or you could use ASCII code and write:
printf("%c", 37);
:)
There's no explanation in this topic why to print a percentage sign. One must type %% and not for example an escape character with percentage - \%.
From comp.lang.c FAQ list · Question 12.6:
The reason it's tricky to print % signs with printf is that % is
essentially printf's escape character. Whenever printf sees a %, it
expects it to be followed by a character telling it what to do next.
The two-character sequence %% is defined to print a single %.
To understand why % can't work, remember that the backslash \ is the
compiler's escape character, and controls how the compiler interprets
source code characters at compile time. In this case, however, we want
to control how printf interprets its format string at run-time. As far
as the compiler is concerned, the escape sequence % is undefined, and
probably results in a single % character. It would be unlikely for
both the \ and the % to make it through to printf, even if printf were
prepared to treat the \ specially.
So the reason why one must type printf("%%"); to print a single % is that's what is defined in the printf function. % is an escape character of printf's, and \ of the compiler.
Use "%%". The man page describes this requirement:
% A '%' is written. No argument is converted. The complete conversion specification is '%%'.
Try printing out this way
printf("%%");

Resources