0

dumb question: lets say I'm assigning a var in a conditional statement. I don't know if the condition will be satisfied and i still want the var to be defined.. whats the correct way of writing this

example:

    NSDecimalNumber *number = [[NSDecimalNumber alloc]init];  // this is pointless right?

    if(x == z){
        number = [whatevernum1 decimalNumberByMultiplyingBy: whatevernum2];
    } else {
        number = [whatevernum2 decimalNumberByDividingBy: whatevernum3];
    }

    // do something with number variable.
2
  • 2
    Since number isn't really given a starting value, what's the point of trying to multiply or divide it by whatevernumber? Commented Jul 23, 2013 at 21:36
  • good catch.. let me edit initial post Commented Jul 23, 2013 at 21:37

3 Answers 3

2

There is no need to initialize number since it will be set. Just do this:

NSDecimalNumber *number;

if(x == z){
    number = [whatevernum1 decimalNumberByMultiplying: whatevernum2];
} else {
    number = [whatevernum2 decimalNumberByDividing: whatevernum3];
}

// do something with number variable.

In your case number will be assigned a value one way or another. But you might have a situation like this:

if (someCondition) {
    // set number to value A
} else if (anotherCondition) {
    // set number to value B
}

Here, it is possible that neither condition is met. In this case you need to deal with this properly by initializing number to nil.

NSDecimalNumber *number = nil;

if (someCondition) {
    // set number to value A
} else if (anotherCondition) {
    // set number to value B
}

if (number) {
    // process result
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to declare the variable but not assign it, like this:

NSDecimalNumber *number;

if(x == z){
    number = [whatevernum1 decimalNumberByMultiplying: whatevernum2];
} else {
    number = [whatevernum2 decimalNumberByDividing: whatevernum3];
}

This tells the compiler that you want to use a variable named number, but don't have a value for it yet. In some cases, you may find it convenient to initialise the variable to nil rather than leaving it as a null pointer.

Comments

0

Normally, as others have pointed out, you would either not initialise (if you can guarantee that you will set a value, eg through an if/else pair), or you would initialise to nil.

In this simple case, a ternary statement would make your code much clearer:

NSDecimalNumber *number = x == z ? [whatevernum1 decimalNumberByMultiplyingBy:whatevernum2] : [whatevernum2 decimalNumberByDividingBy:whatevernum3];

Comments

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.