C语言没有引用,C++才有引用

如果用函数传递参数,实现改变某个数的值。

若用C语言,则传递一个指针值(地址),在函数里把指针所指向的内容重新赋值,指针值不会变。

#include<stdio.h>

int change(int *i)
{
	(*i) = 100;
}

int main()
{
	int a = 60;
	printf("%d\n",a);
	change(&a);
	printf("%d\n",a);
	return 0;
}

若用C++语言,则可以用 ”引用参数“ 

#include<stdio.h>

int change(int &i)
{
	i = 100;
}

int main()
{
	int a = 60;
	printf("%d\n",a);
	change(a);
	printf("%d\n",a);
	return 0;
}



C语言用户真心觉得不太习惯C++的这个特性。



深入一步,如果是要改变或创建一个struct指针类型的节点(例如链表节点、二叉树节点)

C语言

#include<stdio.h>
#include<stdlib.h>

struct tree
{
	int num;
	struct tree *l;
	struct tree *r;
};

int createTreeNode(struct tree **p)
{
	(*p) = (struct tree*)malloc(sizeof(struct tree));
	(*p)->l=NULL;
	(*p)->r=NULL;
	return 0;
}

int main()
{
    struct tree *head=NULL;
    createTreeNode(&head);
    if (head == NULL) 
        printf("is NULL");
    else
        printf("is not NULL");
    
	return 0;
}

C++语言

#include<stdio.h>
#include<stdlib.h>

struct tree
{
	int num;
	struct tree *l;
	struct tree *r;
};

int createTreeNode(struct tree * &p)
{
	p = (struct tree*)malloc(sizeof(struct tree));
	p->l=NULL;
	p->r=NULL;
	return 0;
}
int main()
{
    struct tree *head=NULL;
    createTreeNode(head);
    if (head == NULL) 
        printf("is NULL");
    else
        printf("is not NULL");
    
	return 0;
}


当然,C++兼容C的语法,也就是说以上的代码都可以在C++里运行。


还有一个关于gcc编译器,怎样用C编译器,怎样用C++编译器。

(1)用C编译器的情况: gcc text.c

(2)用C++编译器的情况: g++ test.c 或者 g++ test.cpp 或者 g++ test.c   (也就是用g++命令或者源文件后缀是cpp,则默认是用C++编译器)

  • 11
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值