2

我可以声明一个返回类型不确定的 C 函数(没有 C 编译器警告)吗?返回类型可以是int, float, double,void *等。

undetermined_return_type miscellaneousFunction(undetermined_return_type inputValue);

您可以在其他函数中使用此函数来返回一个值(尽管这可能是运行时错误):

BOOL isHappy(int feel){
    return miscellaneousFunction(feel);
};

float percentage(float sales){
    return miscellaneousFunction(sales);
};

我在找什么:

声明和实现具有未定义返回类型的 C 函数(或 Obj-C 方法)对于面向方面的编程可能很有用。

如果我可以在运行时拦截另一个函数中的 Obj-C 消息,我可能会将该消息的值返回给原始接收者,或者不执行其他操作。例如:

- (unknown_return_type) interceptMessage:(unknown_return_type retValOfMessage){
    // I may print the value here
    // No idea how to print the retValOfMessage (I mark the code with %???)
    print ("The message has been intercepted, and the return value of the message is %???", retValOfMessage);

    // Or do something you want (e.g. lock/unlock, database open/close, and so on).
    // And you might modify the retValOfMessage before returning.
    return retValOfMessage;
}

所以我可以通过一点补充来截取原始消息:

// Original Method
- (int) isHappy{
    return [self calculateHowHappyNow];
}

// With Interception
- (int) isHappy{
    // This would print the information on the console.
    return [self interceptMessage:[self calculateHowHappyNow]];
}
4

4 回答 4

3

您可以使用void *类型。

然后例如:

float percentage(float sales){
    return *(float *) miscellaneousFunction(sales);
}

确保不要返回指向具有自动存储持续时间的对象的指针。

于 2013-09-14T17:11:05.213 回答
1

您可以使用预处理器。

#include <stdio.h>

#define FUNC(return_type, name, arg)        \
return_type name(return_type arg)           \
{                                           \
    return miscellaneousFunction(arg);      \
}

FUNC(float, undefined_return_func, arg)

int main(int argc, char *argv[])
{
    printf("\n %f \n", undefined_return_func(3.14159));
    return 0;
}
于 2013-09-14T17:44:42.043 回答
1

可能是unionthejh建议的

typedef struct 
{
  enum {
      INT,
      FLOAT,  
      DOUBLE
  } ret_type;
  union
    {
       double d;
       float f;
       int i; 
    } ret_val;
} any_type;

any_type miscellaneousFunction(any_type inputValue) {/*return inputValue;*/}

any_type isHappy(any_type feel){
    return miscellaneousFunction(feel);
}

any_type percentage(any_type sales){
    return miscellaneousFunction(sales);
}

在这里ret_type你可以知道返回值的数据类型,并ret_type. i,f,d可以给你相应的值。

所有元素都将使用相同的内存空间,并且只能访问一个。

于 2013-09-14T17:45:13.047 回答
0

Straight C 不支持动态类型变量(变体),因为它是静态类型的,但可能有一些库可以满足您的需求。

于 2013-09-14T17:14:59.743 回答