c不可以是double,float,char*.
goto:
goto主要用于
{...
{...
{....
goto error;
}
}
}
error:
...
2、#define,const
#define和const区别
1、#define C语言
const C语言 C++语言
const常量有数据类型,编译器会进行类型安全检查,而#define没有数据类型,
const的常量可以进行调试,但宏常量不能进行调试.
2、const的使用方法
在全局定义 const float PI=3.1415926
在类中定义
class A
{...
A(int size);
const int SIZE;
};
A::A(int size):SIZE(size)
{
...
}
对参数和函数的定义(const只能修饰输入参数,不能修饰输出参数)
const int x=1; 表示x的值是1,在程序中不能改变;
const int* x; 表示x代表的地址所指向的内容是不能改变得;
int const* x; 与const int* x;的表示的意思一样;
int * const x; 表示x代表的地址是不能改变的;
当是输入参数时,不需要是void Func(const int i),void Func(const int& i),可以是void Func(int i)
因为输入参数采用"值传递"(const int i),由于函数将自动产生临时变量用于复制该参数,该输入参数本来就无需保护,所以不要加const修饰;
不用const int& i的原因在于内部数据类型的参数不存在构造、析构的过程,而复制也非常快,"值传递"和"引用传递"的效率几乎相当.
当是输入参数时,不需要是void Func(const A a),void Func(A a),可以是void Func(A& a)或void Func(const A& a)
不用const A a,A a的原因是函数的效率比较低,因为函数体内将产生A类型的临时对象用于复制参数a,而临时对象的构造、复制和析构过程都需要消耗时间
最好用const A&a的原因是A&a中的a可以被改变,A&a和const A&a的好处在于都不会产生临时对象,效率高;
const A Func(const A&a )const的好处
第一个const表示返回的是个内部产生的对象,它不能被修改
const A Func(...)
{...}
const A a=Func(...);//不能是A a=Func(...);
第二个const表示输入的参数是引用传递,函数内部不会产生临时对象,而且这个对象不能被内部修改
第三个const表示此函数内部的所涉及的数据成员不能修改
class Stack
{
int m_num;
int GetCount(void) const;
int Pop(void);
}
int Stack::GetCount(void) const
{
m_num++;//编译错误,企图修改数据成员m_num;
Pop();//编译错误,企图调用非const函数
}
3、文件拷贝的代码
#include
int main(int argc, char* argv[])
{
printf("Hello World!\n");
FILE* in;
FILE* out;
in=fopen("d:\\1.txt","rb");
out=fopen("d:\\2.txt","wb");
char ch=fgetc(in);
while(!feof(in))
{
fputc(ch,out);
ch=fgetc(in);
}
fclose(in);
fclose(out);
return 0;
}
动态生成内存的代码
正确代码:
void GetMemory(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}
char* GetMemory2(int num)
{
char* p = (char *)malloc(sizeof(char) * num);
return p;
}
错误的代码:
void GetMemory3(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100); // 注意参数是&str,而不是str
strcpy(str, "hello");
cout < < str < < endl;
free(str);
str=NULL;
str=GetMemory2(100);
strcpy(str, "hello");
cout < < str < < endl;
free(str);
str=NULL;
GetMemory3(str, 100); // str 仍然为NULL
strcpy(str, "hello"); // 运行错误
cout < < str < < endl;//运行错误
free(str);//运行错误
}
strcpy代码
char* strcpy(char* strDest,const char* strSrc)
{
if(strDest==NULL||strSrc==NULL) return NULL;
char* pStr=strDest;
while((*strDest++=*strSrc++)!=’\0)
NULL;
return pStr;
}
复合表达式
d = (a = b + c) + r ;
该表达式既求a 值又求d 值.应该拆分为两个独立的语句:
a = b + c;
d = a + r;
if (a < b < c) // a < b < c 是数学表达式而不是程序表达式
