结构总是以C中的分号结尾

Ash*_*wat 0 c structure

我有两种结构.首先是:

struct complex {
    double real, imaginary;
};
Run Code Online (Sandbox Code Playgroud)

我知道它必须用分号结束.

但这一个具有功能

struct complex add_complex(struct complex c1, struct complex c2) {
    struct complex c3;
    c3.real = c1.real + c2.real;
    c3.imaginary = c1.imaginary + c2.imaginary;
    return c3;
}
Run Code Online (Sandbox Code Playgroud)

如果我最后没有包含分号,那么编译器将不会生成错误.为什么?

Mik*_*ike 7

结构定义必须始终以分号结尾.因此,如果;struct complex定义中删除了,则会出现编译器错误.

第二个(add_complex)不是结构定义,它是返回结构的函数.函数末尾没有分号.

  • 我的意思是,如果我写这样的结构复杂add_complex(){}; 那么这个也是如此.为什么?

它是"OK",实际上取决于编译器.我使用过的大多数编译器(例如gcc和Micosoft)都允许这样做,但是可以使用正确的标志显示警告/错误(添加-pedantic到gcc将给出:warning: ISO C does not allow extra ‘;’ outside of a function [-pedantic]你可以添加-Werror)将其转换为错误. )

  • @ ashish2expert:这是一个流浪的分号,在C中是允许但没有意义的. (2认同)