【问题标题】:What kind of code is this? C or C++ [closed]这是什么代码? C 或 C++ [关闭]
【发布时间】:2017-09-17 13:36:53
【问题描述】:

我为自己的练习目的编写了一些代码,但发生了有趣的事情。我最初试图编写 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;
}

【问题讨论】:

  • @WeatherVane: .C 也是 C++ 代码!你的意思是小写.c?
  • @Olaf:"stdafx.h" 的使用意味着 OP 正在 Windows 上编译,其中 foo.cfoo.C 是同一个文件。我不相信 Windows 编译器将 .C 视为 C++ 代码。
  • @Olaf:那又怎样?问题不在于 POSIX。不要假设 .C 暗示 C++ 代码;据我所知,即使 POSIX 也没有指定。这是特定于编译器的约定。
  • 我不知道为什么这个问题会得到如此多的反对票和接近票。这不是一个很好的问题,但似乎足够清楚,我认为它有一个明确而正确的答案。
  • @WeatherVane:标签“C/C++”怎么样。并使用此标签自动关闭问题?可能会节省很多讨论...(我不知道为什么 .C 用于 C++。我从未这样做过,也没有将 .H 用于 C++ 标头。)

标签: c++ c


【解决方案1】:

据我所知,您的代码是有效的 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 是未知类型名称。

【讨论】:

  • 感谢您的回答,感谢大家的热情。
猜你喜欢
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多