Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use double parentheses in init methods, or is 1 == (1)?

Tags:

c

objective-c

What do parentheses do when evaluating some meaning? I have faced this in code, when something is checked and they use

if ( (some condition that returns 1) )
{
code
}

So my question is, does this evaluate to true? I would think that it is always false since (1) does not return anything?

Edit: clarification, question is why double parenthesis in if? I know that 1 is true.

like image 829
Dvole Avatar asked Oct 19 '25 15:10

Dvole


2 Answers

The additional parentheses are used when an assignment is used for its truth value. They allow the compiler to distinguish between

if ((var = expr))

which signals intentional combination of assignment and truth value test, and

if (var = expr)

as an unintentional misspelling of if (var == expr).

The convention, carried over from C and C++, is for the compilers to warn on if (var = expr) as a possible misspelling of if (var == expr). They don't warn on if ((var = expr)), because the extra set of parentheses signals to the compiler that the assignment was intended. As rob mayoff explains, clang has a special case not to warn for certain assignments to self, but for many coders the habit remained.

As others said, the generated code is exactly the same with and without the extra parens.

like image 101
user4815162342 Avatar answered Oct 21 '25 03:10

user4815162342


If you write,

if (self = [super init]) { // Warning
    // ...
}

The compiler will give you a warning, because it thinks you might have mistyped = as ==. If you add a second set of parentheses, the warning goes away.

if ((self = [super init])) { // No warning
    // ...
}

So the extra parentheses are there to make typos less likely. The parentheses do not change the value of the expression.

like image 32
Dietrich Epp Avatar answered Oct 21 '25 03:10

Dietrich Epp