【问题标题】:Can someone explain me why is this C program compiling without errors?有人能解释一下为什么这个 C 程序编译时没有错误吗?
【发布时间】:2022-10-14 03:00:11
【问题描述】:

嘿,我是一名学习 C 编程的学生,只是想知道为什么该程序编译为在线 struct date *newdate, foo(); foo 被声明为具有返回类型结构日期的主函数的本地函数。由于 foo 已经被声明为函数,它应该给出类型冲突的错误,因为 c 不支持函数重载。有人能帮帮我吗。

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

struct date {
    int month;
    int day;
    int year;
};

struct date foo(struct date x) {
    ++x.day;

    return x;
};

int main() {
    struct date today = {10, 11, 2014};
    int array[5] = {1, 2, 3, 4, 5};
    struct date *newdate, foo();
    char *string = "test string";
    int i = 3;

    newdate = (struct date *)malloc(sizeof(struct date));
    newdate->month = 11;
    newdate->day = 15;
    newdate->year = 2014;
    today = foo(today);

    free(newdate);

    return 0;
} 

【问题讨论】:

  • 有哪些错误?
  • 它不会产生任何错误我只是想知道为什么它不会产生错误,因为在第 19 行还有另一个 foo() 声明。 :)

标签: c


【解决方案1】:

foo 被声明为 main 函数的局部函数

不对。它声明但没有定义函数foo 存在,它接受未知数量的参数并返回struct date

此声明与foo 的实际定义兼容,因为返回类型匹配并且声明没有对参数进行任何声明。

【讨论】:

    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多