C++不会编译通过的C程序 示例

虽然C++一直保持着与C兼容,但是依旧有些不同的地方!需要注意纯C程序的问题!


在C++当中,函数未声明先使用会出现编译错误,但是C编译器或许会通过

#include<stdio.h>
int main()
{
   foo(); // foo() is called before its declaration/definition
} 

int foo()
{
   printf("Hello");
   return 0; 
}

在C++中不允许普通指针指向常量,但是C中允许

#include <stdio.h>

int main(void)
{
    int const j = 20;

    /* The below assignment is invalid in C++, results in error
       In C, the compiler *may* throw a warning, but casting is
       implicitly allowed */
    int *ptr = &j;  // A normal pointer points to const

    printf("*ptr: %d\n", *ptr);

    return 0;
}

在C中void指针可以直接赋值给其他类型的指针,但是在C++中要做显示类型转换

#include <stdio.h>
int main()
{
   void *vptr;
   int *iptr = vptr; //In C++, it must be replaced with int *iptr=(int *)vptr; 
   return 0;
}

在C++程序中const常量必须初始化,否则编译错误,但C中允许

#include <stdio.h>
int main()
{
    const int a;   // LINE 4
    return 0;
}

很不幸的是,在C中我们可以使用C++的关键字new等作为变量名

#include <stdio.h>
int main(void)
{
    int new = 5;  // new is a keyword in C++, but not in C
    printf("%d", new);
}

C++ 会做更严格的类型检查,比如下面的代码在C中通过,但是C++中编译失败

#include <stdio.h>
int main()
{
    char *c = 333;
    printf("c = %u", c);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值