C++条件编译

2014-11-24 00:56:18 · 作者: · 浏览: 3

条件编译:
一般情况下,源程序中所有的行都参加编译。但有时希望对其中一部分内容只在满足一定条件下才进行编译,即对一部分内容指定编译条件,这就是“条件编译”(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
using namespace std;
#define upper 1
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"< cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<"< }else{
cout<<"data erroe"< }
#else
cout<<"uppercase to lowercase"< cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<"< }else{
cout<<"data erroe"< }
#endif
cout<<"Good Night~"< return 0;
}

#include
using namespace std;
#define upper 1
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"< cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<"< }else{
cout<<"data erroe"< }
#else
cout<<"uppercase to lowercase"< cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<"< }else{
cout<<"data erroe"< }
#endif
cout<<"Good Night~"< return 0;
}


\


代码2:

[cpp]
#include
using namespace std;
#define upper 0
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"< cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<"< }else{
cout<<"data erroe"< }
#else
cout<<"uppercase to lowercase"< cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<"< }else{
cout<<"data erroe"< }
#endif
cout<<"Good Night~"< return 0;
}

#include
using namespace std;
#define upper 0
int main(){
char a;
#if upper
cout<<"lowercase to uppercase"< cout<<"please input a char:";
cin>>a;
if(a>='a'&&a<='z'){
cout<"< }else{
cout<<"data erroe"< }
#else
cout<<"uppercase to lowercase"< cout<<"please input a char:";
cin>>a;
if(a>='A'&&a<='Z'){
cout<"< }else{
cout<<"data erroe"< }
#endif
cout<<"Good Night~"< return 0;
}


\


分析:
代码1和代码2的区别是upper的值分别是1和0,运行结果也证明了分别编译了语句段1和语句段2。
[cpp]
cout<<"Good Night~"<

cout<<"Good Night~"<