如果用函数传递参数,实现改变某个数的值。
若用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++编译器)