C与C++的差异
1. sizeof
在C里,字符常量和枚举符的大小都是sizeof(int);而在C++里,sizeof('a')等于sizeof(char),且C++实现可以自己为枚举选择最合适的大小。
在C++里,在内层作用域里声明的结构名将屏蔽位于外层作用域的对象、函数、枚举或者类型的名字。例如:
#ifdef __cplusplus
extern “C” {
#endif
int x[99];
int main()
{
struct x {int a;};
sizeof(x); /* 在C中是数组x的大小(99*sizeof(int)),在C++中是结构x的大小 */
}
#ifdef __cplusplus
}
#endif
extern “C” {
#endif
int x[99];
int main()
{
struct x {int a;};
sizeof(x); /* 在C中是数组x的大小(99*sizeof(int)),在C++中是结构x的大小 */
}
#ifdef __cplusplus
}
#endif
2. 函数声明
在C里,大部分函数可以在没有预先声明的情况下调用。例如:
#ifdef __cplusplus
extern "C" {
#endif
main ()
{
double sq2 = sqrt(2);
printf(“The square root of 2 is %g"n”, sq2);
}
#ifdef __cplusplus
}
#endif
extern "C" {
#endif
main ()
{
double sq2 = sqrt(2);
printf(“The square root of 2 is %g"n”, sq2);
}
#ifdef __cplusplus
}
#endif
在C里,对于那些声明中没有描述参数类型的函数,它们就可以取任意个数的任意类型的参数:
void f(); /* 未提到参数类型 */
void g()
{
f(2);
}
void g()
{
f(2);
}
在C语言里,函数定义可以采用另一种语法,在参数表之后另外描述参数的类型:
void f(a, p, c)
char *p;
char c;
{
return;
}
char *p;
char c;
{
return;
}
3. 数据类型
在C和C++标准以前的版本中,类型描述符默认为int,在上一个函数f中,a的类型就默认为int型的。
const a = 7; /* 在C中假定a的类型为int */
C允许将struct定义用在返回值类型和参数类型声明中。例如:
struct S{int x, y;} f();
void g(struct S{int x,y;} y);
void g(struct S{int x,y;} y);
在C里可用将整数赋给枚举类型的变量:
enum Direction {up, down};
enum Direction d = 1;
enum Direction d = 1;
在C里,一个全局数据对象可以在同一个编译单位里声明多次,不必使用extern声明符,条件是在这些声明中至多只有一个提供了初始化表达式,在这种情况下就认为对象只定义了一次。在C++中,每个实体必须定义恰好一次:
int i;
int i;
int i;
int i = 0;
int i; /* 这在C里是允许的 */
int i;
int i;
int i = 0;
int i; /* 这在C里是允许的 */
在C里,void* 可以作为对任意指针类型的变量赋值操作右边的运算对象,或用于对这种变量的初始化。
void f(int n)
{
int *p = malloc(n*sizeof(int));
}
{
int *p = malloc(n*sizeof(int));
}
在C里,嵌套结构的名字与它们嵌套于其中的结构放在同一作用域里。例如:
struct S
{
struct T{/*
*/};
/*
*/
}
struct T x;
{
struct T{/*
*/};/*
*/}
struct T x;
在C里,数组可以用于多于它所需元素个数的初始式进行初始化。例如:
char v[5] = "Hello";

浙公网安备 33010602011771号