我出于自己的练习目的编写了一些代码,但有趣的事情发生了。我最初尝试编写 C++ 代码,但是我忘记了包含 Streamio 库和使用命名空间 std,然后我在编码过程中一直使用 printf() 函数。
我认为对我来说最困惑的部分是我使用 .cpp 扩展名并使用 VS 2015 编译器编译这个程序,但我实际上是用 C 风格编写的。有人可以告诉我我写的是 C 或 C++ 代码吗?
这是源代码:
#include "stdafx.h"
#include <stdlib.h>
typedef struct node
{
int data;
node *next;
}node;
node *create()
{
int i = 0;
// Each variable must be assign to some value in the function
node *head, *p, *q = NULL;
int x = 0;
head = (node *)malloc(sizeof(node));
while (1)
{
printf("Please input the data: ");
scanf_s("%d", &x);
if (x == 0)
break;
p = (node *)malloc(sizeof(node));
p->data = x;
if (++i == 1) {
head->next = p;
}
else
{
q->next = p;
}
q = p;
}
q->next = NULL;
return head;
}
void printList(node head)
{
node *tmp = &head;
int counter = 0;
printf("Print out the list: \n");
while (tmp->next != NULL) {
tmp = tmp->next;
counter++;
//surprise to me printf() is pretty advance...
printf("%d item in the list: %d\n",counter, tmp->data);
}
}
int main()
{
printList(*create());
return 0;
}
最佳答案
据我所知,您的代码是有效的 C++。它不是有效的 C,但只需一点点努力就可以使其成为有效的 C。
C几乎是 C++ 的子集,但是有些有效的 C 代码不是有效的 C++ 代码,当然还有大量有效的 C++ 代码不是有效的 C 代码。
使您的代码与 C 一样无效的一件事是使用名称 node
:
typedef struct node
{
int data;
node *next;
}node;
在 C++ 中,struct node
定义使类型可见为 struct node
或 node
。在 C 中,struct
定义本身仅创建名称struct node
。在 typedef
完成之前,名称 node
不可见 - 它不在您定义 node *next;
的位置。
如果您使用 .c
后缀重命名源文件并将其编译为 C,编译器会提示 node
是未知类型名称。
关于c++ - 这是什么样的代码? C 或 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43527648/