众所周知,C++ 里可以使用这样的方式来代替相应位运算和逻辑运算符:
a = a and 1;
a = a xor b;
但是 C 语言有时候就会 CE:
错误:expected ‘,’ or ‘;’ before ‘and’
a = a and 1;
(报错信息来自洛谷IDE)
后来我在 VS 上发现,当开万能头使用这些运算符的时候,它们会变成紫色,也就是说,它们可能是以宏的形式被定义过。
通过 VS 强大的功能,我发现这些运算符确实有宏定义,在 iso646.h
中。
内容如下:
/* iso646.h standard header */
#pragma once
#ifndef _ISO646
#define _ISO646
#ifndef RC_INVOKED
#if !defined(__cplusplus) || defined(_MSC_EXTENSIONS)
#define and &&
#define and_eq &=
#define bitand &
#define bitor |
#define compl ~
#define not !
#define not_eq !=
#define or ||
#define or_eq |=
#define xor ^
#define xor_eq ^=
#endif /* !defined(__cplusplus) || defined(_MSC_EXTENSIONS) */
#endif /* RC_INVOKED */
#endif /* _ISO646 */
/*
* Copyright (c) by P.J. Plauger. All rights reserved.
* Consult your license regarding permissions and restrictions.
V6.50:0009 */
原来 C 语言没有这些运算符,而标准库以这样的形式把这些运算符定义了一遍。百度百科说法如下:
iso646.h是C标准函数库中的头文件,定义了一批C语言常见运算符的可选拼写。iso646.h是作为C90标准的修正案于1995年增补的。
也就是说,对于这样的代码,C 语言编译通过:
#include<iso646.h>
int a;
int main()
{
a = a xor 1;
}
但是加上一行
#undef xor
C++ 直接把它们定成了运算符,就不会影响什么,但是 C 当场暴毙。
太震撼了。