枚舉類型:
1.1枚舉類型聲明int 類型的常量,使用關鍵字enum。
使用枚舉類型的目的是提高程序的可讀性
#include <stdio.h>
int main(void){
enum a {red,blue,green,populer,white,blach};
enum a c;
c = blue;
printf("%d\n",c);
}
結果 = 1;
#include <stdio.h>
int main(void){
enum a {red = 100,blue,green,populer,white,blach};
enum a c;
c = blue;
printf("%d\n",c);
}
結果 = 101
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
enum spectrum { red,orange,yellow,green,blue,violet};
const char *colors[] = {"red","orange","yellow","green","blue","violet"};
#define LEN 30
int main(void){
char choice[LEN];
enum spectrum color;
bool color_is_found = false;
puts("Enter a color (empty line to quiet):");
while(gets(choice)!= NULL & choice[0] != '0'){
for(color = red;color <= violet;color ++){
if(strcmp(choice,colors[color]) == 0){
color_is_found = true ;
break;
}
}
if(color_is_found)
switch(color){
case red : puts("rose are red");break;
case orange: puts("poppies are orange");break;
case yellow: puts("sunflower is yellow");break;
case green : puts("grass is green"); break;
case blue : puts("bluebells is blue");break;
case violet: puts("violet is voilet"); break;
}
else
printf("i do not know about the color %s.\n",choice);
color_is_found = false;
puts("next colors please(empty line to quiet):");
}
puts("goodbye!");
return 0;
}
名字相同但是具有不同的作用域不會起衝突,名字空間是分類別的。這意味着可以在同一個作用域內對一個變量和一個標記使用同一個名字,而不會產生錯誤