c++ - 这是什么样的代码? C 或 C++

标签 c++ c

我出于自己的练习目的编写了一些代码,但有趣的事情发生了。我最初尝试编写 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 nodenode。在 C 中,struct 定义本身仅创建名称struct node。在 typedef 完成之前,名称 node 不可见 - 它不在您定义 node *next; 的位置。

如果您使用 .c 后缀重命名源文件并将其编译为 C,编译器会提示 node 是未知类型名称。

关于c++ - 这是什么样的代码? C 或 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43527648/

相关文章:

c - 简单的开源画图程序

c++ - 通过引用为 Bool 设置默认值

c++ - 在 C++ 中,是否定义了通过 char* 删除基本类型(例如 uint32_t)的行为?

c++ - 在 C++ 中从文件中读取网格

c++ - 构造函数中的初始化列表问题

c++ - C 编程 - 堆栈和堆数组声明

c - ftruncate 无法与 msys2 一起正常工作

C-strcpy 指针

c - 动态调度,C

c - 指向 uint 数组的指针