一个字符串直接量实际上是一个const char 的数组。它包含的元素个数比字面上的字符数多1.这个额外的字符是'\0';
const char hello[]="hello";//编译器自动加上去
等价于:
const char hello[]={ 'h','e','l','l','o','\0' };
初始化字符指针数组。
假定我们要把数字表示的成绩转换为字母表示的成绩,根据下面的规则:
如果成绩不低于 9 0 80 70 60 0
对应字母成绩: A B C D E
下面是一个完成转换的程序:
#include<iostream> #include<string> using namespace std; string letter_grade(double grade) { static const double numbers[]={ 90,80,70,60,0}; static const char* const letters[]={ "A","B","C","D","E" }; //compute the size of array static const size_t ngrades=sizeof(numbers)/sizeof(*numbers); for(size_t i=0;i<ngrades;i++) { if(grade>=numbers[i]) return letters[i]; } return "不符合要求"; } int main() { int n; cin>>n; cout<<letter_grade(n); }
使用static关键字,局部变量被声明为static,他的生存空间就可以不受函数的现在,我们只会在第一次调用函数时,创建并初始化static声明的变量,后来所有的调用都是第一次调用创建的。
求数组大小
sizeof(arr)/sizeof(*arr) 或 sizeof(arr)/sizeof(arr[0]);