Declared but unset variable evaluates as true?

瘦欲@ 提交于 2019-12-20 02:32:54

问题


I was doing a simple calculator with the following code. Right now it executes perfectly. When I tried to change things around, however, it doesn't work. I used BOOL program to check whether to continue asking for input from the person or finish the program.

If I change the expression of while statement to just (program) and change YES/NO in the program statements, why does the code fail to do what is inside the while?

// A simple printing calculator
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]
    Calculator *deskCalc = [[Calculator alloc] init];
    double value1;
    char operator        
    BOOL program;

    [deskCalc setAccumulator: 0];

    while (!program) {
    NSLog (@"Please type in your expression");
    scanf (" %lf %c", &value1, &operator);
    program = NO;

        if (operator == '+') {
            [deskCalc add: value1];
        }
        else if (operator == '-') {
            [deskCalc subtract: value1];
        }
        else if (operator == '*' || operator == 'x') {
            [deskCalc multiply: value1];
        }
        else if (operator == '/') {
            if (value1 == 0)
                NSLog (@"Division by zero!");
            else
                [deskCalc divide: value1];
        }
        else if (operator == 'S') {
            [deskCalc set: value1];
        }
        else if (operator == 'E') {
            [deskCalc accumulator];
            program = YES;
        }
        else {
            NSLog (@"Unknown operator");
        }
    }

    NSLog (@"The result is %f", [deskCalc accumulator]);

    [deskCalc release];

    [pool drain];
    return 0;
}

回答1:


You haven't set the initial value of program, so it defaults to a garbage value which just happens to be non-zero.

Set the initial value of program when you declare it:

BOOL program = NO; // or YES, whichever is appropriate



回答2:


It is always a good practice to initialize all your variables when you declare them.

Also using scanf for input may be overdoing it, if I were you I would use fgets and then extract the information from the string using strtok. That way even if the user puts his elbow on the keyboard you will not have to worry. Alternatively if you are fond of scanf use sscanf on that string instead of strtok.



来源:https://stackoverflow.com/questions/7518686/declared-but-unset-variable-evaluates-as-true

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