Advanced C language: 13, continuation characters and escape characters

The continuation character (\) in C language is a powerful tool to indicate the behavior of the compiler.

The compiler will remove the backslash (\), and the characters following the backslash will automatically continue to the previous line;

When connecting words, there must be no space after the backslash, and no space before the next line of the backslash; (an error will be reported)

backslash and newline separated by space // warning adds an extra space after the continuation character

Continuation characters are suitable for use when defining macro code blocks.

Source code:

#include <stdio.h>

#define SWAP(a,b) {int temp=a; a=b; b=temp;}

intmain()
{
	int a=1;
	int b=2;
	int c=3;
	
	SWAP(a,b);
	
	printf("a= %d, b= %d\n", a, b);
	
	SWAP(b, c);
	
	printf("b= %d, c= %d\n", b, c);

	return 0;
}
Expand a macro block with a continuation character:
#define SWAP(a,b) 		                \
{						\
		int temp=a;		        \
		a=b;			        \
		b=temp; \//The meaning of the macro definition content can be seen at a glance through the continuation character
}

Escapes

The escape character (\) in the C language is mainly used to represent no echo characters, and can also be used to represent regular characters
  \n carriage return line feed
  \t Jump horizontally to the next tab position
  \v vertical tab
  \b backspace
  \r Enter
  \f Feed form feed
  \\ backslash character "\"
  \' single quote character
  \a Ring the bell
  \ddd The character represented by 1~3 octal digits
  \xhh Character represented by 1~2 hexadecimal digits

Observe the following code and judge the output:

char enter = '\n';

char *p = "\141\t\x62"; //141 in octal, for decimal 97, ANSIC code of lowercase character a

printf("%s", p);
printf("%c", enter); //No echo characters directly wrap

The output is:

delphi@delphi-vm:~/will$ ./a.out
a	b

That is, escape characters can appear between single and double quotes, with their normal meaning.

#include <stdio.h>

intmain()
{
    char c = '\n';
    char* s = "\n\n";
    
    printf("%c\n", c);
    printf("%s\n", s);
    
    return 0;
}

summary:

    The backslash (\) in C language acts as both a continuation character and an escape character

    When used as a continuation character, it can appear directly in the program

    When used as an escape character, it must appear between single or double quotes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325576637&siteId=291194637