What is the intention of putting return values in parentheses in C/Objective-C?

家住魔仙堡 提交于 2019-12-22 08:34:31

问题


I've come across some code that surrounds the return value from a method/function in parentheses.

What does that do?

The code I saw took an image, resized it and then returned it.

- (UIImage *)resizeImage:(UIImage *)image
{
    //
    // some fascinating, but irrelevant, resizing code here
    //

    return (image);
}

回答1:


At least as far as C is concerned, it makes no difference. The parens aren't necessary, but they don't change the meaning of the return statement. The grammar of the return statement is

return-statement:
    return expressionopt ;

and one of the productions of the expression non-terminal is a parenthesized-expression, or ( expression ).




回答2:


Nothing. It is completely useless.

It overrides operator precedence, yet no operator will have a lower precedence than "return".




回答3:


The short answer is simply that it's a style choice, like using "/* comments */" instead of "//comments"




回答4:


In your case it is equivalent of typing the return without the parentheses. Typically, you would use parentheses for type casting, or if you want to treat an expression as an independent block.

For example:

// This is an untyped pointer to an instance of SomeClass
void* ptr = instance;

// In order to let the compiler know that ptr is an instance of SomeClass
// we cast it, and then we put the cast in parentheses to be able to access
// a property on the result of the cast.
return ((SomeClass *)ptr).someproperty;


来源:https://stackoverflow.com/questions/3906686/what-is-the-intention-of-putting-return-values-in-parentheses-in-c-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!