6

Using apple's example from the docs

float (^oneFrom)(float);


oneFrom = ^(float aFloat) {

  float result = aFloat - 1.0;

  return result;

};

I get two errors:

  1. Redefinition of 'oneFrom' with a different type: 'int' vs 'float(^)(float)'
  2. Type specifier missing, defaults to 'int'

Also from the doc..

If you don’t explicitly declare the return value of a block expression, it can be automatically inferred from the contents of the block. If the return type is inferred and the parameter list is void, then you can omit the (void) parameter list as well. If or when multiple return statements are present, they must exactly match (using casting if necessary).

2 Answers 2

3

You can't define blocks on file scope, only in functions. This works as expected:

void foo (void)
{
    float (^oneFrom)(float);
    oneFrom = ^(float aFloat) {
        float result = aFloat - 1.0;
        return result;
    };
}
Sign up to request clarification or add additional context in comments.

6 Comments

My understanding was that blocks are similar to C function pointers. Shouldn't I be able to declare it in the header file?
@estobbart No, blocks are a much more complex concept than function pointers. Most important: they carry data, so they have to be dynamically allocated on the stack or heap. C does not allow for initialization of objects with static storage duration, so you can't define a block on file scope.
@estobbart You can, of course, declare a block type variable using extern in a header file. You cannot define a block, though.
Understood. There's a number of examples of declaring a block. Is there a situation where a block declaration is used? It looks like blocks are almost always used as block literals.
One example would be a property of block type, for example NSFileHandle's readabilityHandler.
|
-1

that block doesnt have a return type, and the default return type is void, you will need to go

float (^oneFrom)(float);

oneFrom = ^ float (float aFloat) {

  float result = aFloat - 1.0;

  return result;

};

here is a better blocks example

4 Comments

This example still reports the same errors. Am I missing something obvious?
No. The block has a return type which is deducted from the actual return statement. It has the correct type of float.
ah, yes my mistake, ive always implicitly done it for some reason. your answer is probably the real solution here as well, didnt think about where the block would be defined
@nikolai I think you mean "deduced" not "deducted". Perhaps "inferred" would be a better choice of words?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.