写一个C语言程序,编译不在C++中

虽然C++被设计成与C具有向后兼容性,但是当用C++编译器编译时,会有许多C程序会产生编译器错误。以下是不会在C++中编译的C程序列表:

null
  1. 在声明之前调用函数
  2. 使用常量变量的普通指针
  3. 使用类型化指针
  4. 在不初始化的情况下声明常量值
  5. 使用特定关键字作为变量名
  6. 严格的类型检查
  7. main()的返回类型

以下将详细讨论这些要点:

1) 在声明之前调用函数: 在C++中,在声明函数之前调用函数是一个编译错误。但在C语言中,它可以编译。(见 当函数在C中声明之前被调用时会发生什么? )

C

// C Program to demonstrate calling
// a function before declaration
#include <stdio.h>
// Main starts
int main()
{
// fun() is called before its
// declaration/definition
fun();
}
// Function Declaration
int fun()
{
printf ( "Hello" );
return 0;
}


2) 使用带有常量变量的普通指针: 在C++中,当使用一个普通指针指向一个const变量时,编译器错误就会产生,但是在C.中是允许的。 必读—— C中的常量限定符 )

C

// C Program to demonstrate using a
// normal pointer with const variable
#include <stdio.h>
// Main starts
int main()
{
// A normal pointer points to const
int const j = 20;
int * ptr = &j;
// The below assignment is invalid in C++,
// results in error.In C, the compiler may
// throw a warning, but casting is implicitly allowed
printf ( "*ptr: %d" , *ptr);
return 0;
}


3) 使用类型转换指针: 在C语言中,一个空指针可以直接分配给其他指针,比如int*,char*。但是在C++中,空指针必须显式类型化。

C

// C Program to demonstrate
// using typecasted pointers
#include <stdio.h>
// Main starts
int main()
{
void * vptr;
// In C++, it must be
// replaced with int *iptr=(int *)vptr;
int * iptr = vptr;
return 0;
}


注: 这是我们在使用malloc()时注意到的。malloc()的返回类型为void*。在C++中,我们必须显式地将MalCube()的返回值键入适当的类型,例如“int *P=(int *)Maloc(siZeof(int)”)。在C语言中,类型转换是不必要的。

4) 在不初始化的情况下声明常量值: 在C++中,const变量必须初始化,但在C中不必初始化。下面的程序编译和运行在C中,但在C++中编译失败。

C

// C Program to demonstrate declaring
// constant values without initializing:
#include <stdio.h>
// Main starts
int main()
{
const int a;
return 0;
}


5) 使用特定关键字作为变量名: 在C中,特定的关键字可以用作变量名,但是,C++中不可能。下面的程序将不在C++中编译,而是在C.编译

C

// C Program to demonstrate using
// specific keywords as variable names
#include <stdio.h>
// Main starts
int main( void )
{
// new is a keyword in C++
// but not in C
int new = 5;
printf ( "%d" , new );
}


类似地,我们可以使用其他关键字,比如 删除,显式,类

6) 严格的类型检查: C++比C做更严格的类型检查。例如,下面的程序在C中编译,但不是在C++中编译。在C++中,我们得到编译器错误“从int”到“char *”的无效转换。

C

// C Program to demonstrate
// strict type checking
#include <stdio.h>
// Main starts
int main()
{
char *c = 333;
printf ( "c = %u" , c);
return 0;
}


7) main()的返回类型: 在C++中,main函数需要返回类型的int,但是C++中的C.不是这样的,我们不能将返回类型用作“空”。

C

// C Program to demonstrate that
// 'void' can be used as a return type
// for main()
#include <stdio.h>
// Main starts
void main()
{
printf ( "Hello World" );
}


8) 下面的程序在C中编译,但不在C++中编译。(见 更多参考。)

C

// C Program that won't compile in C++
#include <stdio.h>
void func()
{
// definition
}
// Main starts
int main()
{
func();
func(2);
}


说明: 在C++中,函数()与FUNC(Valk)等价,但是在C中,函数()()等于FUNC(…)。

本文由 阿比拉蒂 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享