【问题标题】:Hidden/Anchored argument of a function?函数的隐藏/锚定参数?
【发布时间】:2020-02-02 06:22:15
【问题描述】:

我想要一个额外的函数来检查输入函数是否返回 0。如果是这样,额外的函数将退出程序并打印它发生的行号。我是这样写的:

 void check( int function_return_value, int line_with_error )
    {
        if(!function_return_value )
        {
            printf("Error on line %d\n", line_with_error );
            exit(EXIT_FAILURE);
        }
    }

line_with_error 在我的主代码文件中收到 LINE 宏的值,它看起来像这样

check( function(), __LINE__ );

但是我不希望“检查”函数接受 2 个参数,只有 1 个带有函数返回值。有没有办法以某种方式“隐藏”第二个参数,以便函数知道 LINE 宏总是会去那里,但我不必每次都写它?

附: LINE 将采用代码中写入的行号。我不能把它放在“检查”函数中,因为它总是引用函数声明中的行

【问题讨论】:

  • 唯一的方法是使用一个宏扩展为带有__LINE__参数的调用。
  • #define CHECK_MACRO(x) check ((x), __LINE__) 之类的有什么问题?

标签: c++ c arguments


【解决方案1】:

使用宏:

#define check(x) (check_2args((x), __LINE))

void check_2args( int function_return_value, int line_with_error )
{
    if(!function_return_value )
    {
        printf("Error on line %d\n", line_with_error );
        exit(EXIT_FAILURE);
    }
}

【讨论】:

  • 工作正常。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多