不带括号的C函数调用 [英] C function call without bracket

查看:140
本文介绍了不带括号的C函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的C程序:

Here is a simple C program:

#include <stdio.h>

int main(void)
{
    printf("Display something\n");
    fflush stdout;
    return 0;
}

使用msys2 mingw-w64 gcc版本7.3.0和选项-Wall进行编译,一切正常,就像第五行是fflush(stdout);.

Compiled with msys2 mingw-w64 gcc version 7.3.0 and option -Wall and everything works fine, just as if the 5th line was fflush(stdout);.

我试图用自己的函数重现这样的调用,但是我得到了完全可以预期的错误

I tried to reproduce such a call with my own function, but I get the perfectly expected error

src/main.c: In function 'int main(int, char**)':
src/main.c:5:18: error: expected ';' before 'parameter'
  custom_function parameter;
                  ^~~~~~~~~

那么,fflush函数会发生什么?有人可以向我解释吗?您是否与其他C编译器具有相同的行为?

So, what happens with the fflush function? Can somebody explain me? Do you have the same behavior with other C compilers?

推荐答案

让我们看看预处理器的输出(使用MinGW和gcc -E test.c命令行):

Let's see preprocessor output (using MinGW, and gcc -E test.c command line):

   fflush 
# 5 "test.c" 3
          (&(* _imp___iob)[1])
# 5 "test.c"
                ;

如您所见,

stdout是一个宏,该宏用括号扩展为(&(* _imp___iob)[1]).

as you see stdout is a macro which expands to (&(* _imp___iob)[1]) with parentheses.

所以编译器使用这些括号并且语法可以.

so the compiler uses those parentheses and the syntax is okay.

但这仅是因为宏魔术,以及大多数宏都由括号保护的事实,以避免与其他令牌(例如,运算符的优先级)产生副作用

But that's only because of macro magic, and the fact that most macros are protected by parentheses to avoid side-effects with other tokens (operator precendence for instance)

您可以使用以下简单代码重现它,而无需任何包含:

You can reproduce that without any includes with this simple code:

#define arg ("hello")

void f(const char *x)
{
}

int main(int argc, char** argv)
{
    f arg;
    return 0;
}

这当然是不好的做法,会使IDE(和人类)感到困惑,所以请不要这样做.

Of course this is bad practice, confuses IDEs (and humans), so just don't do it.

这篇关于不带括号的C函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆