views:

290

answers:

4
- (id)methodThatReturnsSomething
{
    @synchronized(self) {
        return nil;
    }
}

When I do this on Xcode, it returns me a warning: "Control reaches end of non-void function"

Is there any problem with that code?

A: 

I don't understand what you want to do in your code, but

- (id)methodThatReturnsSomething
{
    @synchronized(self) {
    }
    return nil;
}

should have the same effect (postponing the return until the lock associated to self is freed), without the compiler warning.

But: what did you want to do? You don't have to put a @synchronized in this manner.

Yuji
This synchronized stands the risk of being completely removed by the optimizer, which of course shouldn't make any difference anyhow - like you say, "what did problem did you want to solve"?
calmh
A: 

Yes,

The @synchronized block is similar to doing this (my terrible pseudocode)

- (id)methodThatReturnsSomething
{
    if ([self notlocked]) {
        [self lock]
        return nil;
        [self unlock]
    }
}

You can see that if another function call is made, then it will reach the last } without returning something.

Stephen Furlani
Where did you get the idea that the `@synchronized` block is not entered if another thread has entered it? It is supposed to block until it can get the lock, see the [documentation](http://developer.apple.com/mac/library/documentation/cocoa/conceptual/objectivec/Articles/ocThreading.html#//apple_ref/doc/uid/TP30001163-CH19-BCIIGGHG).
Georg Fritzsche
aaaaaaaaaaaand what part of "terrible pseudocode" did you not understand?
Stephen Furlani
You still say - outside of your pseudo-code - that it could leave the function without returning something. But the only case where the return-statement isn't performed is if an exception is thrown in the block, in which case it doesn't matter anyway.
Georg Fritzsche
Eh, well if the OP is posting bogus errors, then he'll get bogus answers. I honestly have no other idea why it would throw that warning if there's no other exit path for the code.
Stephen Furlani
+1  A: 

The synchronization in the code as posted is redundant but there is no problem with it as such:
@synchronized blocks are either exited normally or through exceptions. As you already have a return statement in it, another statement after the block is not needed.

Georg Fritzsche
The code, as posted, is perfectly meaningful. It just causes an unnecessary lock to be taken.
bbum
@bbum: True, thats what i meant to say.
Georg Fritzsche
+9  A: 

It barfs up a compiler warning because of a bug in some versions of the compiler that are fixed in other / later versions of the compiler.

In this case, yes, you really did stumble upon a compiler bug.

bbum