Objective-C enter block type in another, getting unexpected result

typedef (void (^blockType)());

I need blocks with different types of arguments in the same type blockTypeand call it as the original type later. But there is a problem when creating a lock type.

The following code works well with any type of argument, ...

((blockType)^(BOOL b) {
    NSLog(@"BOOL: %d", b);
})(YES); // >> BOOL: 1
((blockType)^(int i) {
    NSLog(@"int: %d", i);
})(1); // >> int: 1
((blockType)^(double f) {
    NSLog(@"double: %f", f);
})(1.0 / 3); // >> double: 0.333333
((blockType)^(NSString *s) {
    NSLog(@"NSString *: %@", @"string");
})(1.0 / 3); // >> NSString *: string

except float :

((blockType)^(float f) {
    NSLog(@"float: %f", f);
})(1.0f); // >> float: 0.000000
((blockType)^(float f) {
    NSLog(@"float: %f", f);
})(1.0f / 3); // >> float: 36893488147419103232.000000

but this is fine without casting:

(^(float f) {
    NSLog(@"float without casting: %f", f);
})(1.0 / 3); // >> float without casting: 0.333333

How to explain and solve the problem?

+4
source share
2 answers

, . ( , "" Obj-C C, (. )):

void test()
{
    void (*pEmpty)();
    pEmpty = functionFloat;
    pEmpty(1.0f / 3);
}

void functionFloat(float f)
{
    printf("float: %f", f);
}

test, , "" . .

void (*pEmpty)();

void (*pEmpty)(void);

. , void void-, . (void (^)(void) (void (^)().

C Standard:

, , . ยง6.7.6.3-14 ( .134)

, , , , .

:

; . , , undefined.
ยง6.3.2.3-8 ( .56)

, ( ), , , undefined.
ยง6.5.2.2-9 ( .82)

, , , @jtbandes: , .

+4

: (void (^)()), (void (^)(double)).

Resolve: (void (^)(float)).

0

Source: https://habr.com/ru/post/1666063/


All Articles