条件编译:
一般情况下,源程序中所有的行都参加编译。但有时希望对其中一部分内容只在满足一定条件下才进行编译,即对一部分内容指定编译条件,这就是“条件编译”(conditional compile)。
常用形式:
条件编译命令常用的有以下形式:
(1)
#ifdef 标识符
程序段1
#else
程序段2
#endif
它的作用是当所指定的标识符已经被#define命令定义过,则在程序编译阶段只编译程序段1,否则只编译程序段2。#endif用来限定#ifdef命令的范围。其中,#else部分也可以没有。
(2)
#ifndef 标识符
程序段1
#else
程序段2
#endif
它的作用是当所指定的标识符没有被#define命令定义过,则在程序编译阶段只编译程序段1,否则只编译程序段2。这种形式与第一种形式的作用相反。
(3)
#if 表达式
程序段1
#else
程序段2
#endif
它的作用是当所指定的标识符值为真(非零)时,则在程序编译阶段只编译程序段1,否则只编译程序段2。可以事先给定一定条件,使程序在不同的条件下执行不同的功能。
例子:
题目:输入一个字母字符,使之条件编译,使之能根据需要将小写字母转化为大写字母输出,或将大写字母转化为小写字母输出。
代码1
[cpp]
#include<iostream>
using namespace std;
#define upper 1
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<<a<<"===>"<<char(a-32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#else
cout<<"uppercase to lowercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<<a<<"===>"<<char(a+32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#endif
cout<<"Good Night~"<<endl;
return 0;
}
#include<iostream>
using namespace std;
#define upper 1
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<<a<<"===>"<<char(a-32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#else
cout<<"uppercase to lowercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<<a<<"===>"<<char(a+32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#endif
cout<<"Good Night~"<<endl;
return 0;
}
代码2:
[cpp]
#include<iostream>
using namespace std;
#define upper 0
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<<a<<"===>"<<char(a-32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#else
cout<<"uppercase to lowercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<<a<<"===>"<<char(a+32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#endif
cout<<"Good Night~"<<endl;
return 0;
}
#include<iostream>
using namespace std;
#define upper 0
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<<a<<"===>"<<char(a-32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#else
cout<<"uppercase to lowercase"<<endl;
cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<<a<<"===>"<<char(a+32)<<endl;
}else{
cout<<"data erroe"<<endl;
}
#endif
cout<<"Good Night~"<<endl;
return 0;
}
分析:
代码1和代码2的区别是upper的值分别是1和0,运行结果也证明了分别编译了语句段1和语句段2。
[cpp]
cout<<"Good Night~"<<endl;
cout<<"Good Night~"<<endl;这个语句是在#endif之后的语句,这说明#endif只是表示了#if——#else语句的结束,而不是编译的结束,也就是说#endif之后的语句都会正常的编译和执行。