Declaring variables outside loop/IF structures in C

前端 未结 2 838
名媛妹妹
名媛妹妹 2021-01-25 08:51

I\'m new to the C language, rather programming overall. I was wondering why is it that when I declare a variable to be used within an if statement OUTSIDE the structure, that th

2条回答
  •  耶瑟儿~
    2021-01-25 09:02

    The relevant code boils down to:

    double tax;
    netpay = grosspay - grosspay * tax;
    tax = 0.10;
    printf("Net pay: $%.2f\n", netpay);
    

    The problem with this is that statements in a program are executed in the order you've written them (at least within a function, barring special control flow statements such as continue or goto).

    Thus:

    1. First we define a local variable called tax, which is uninitialized.
    2. Then we set netpay to the result of grosspay - grosspay * tax. This is already wrong because tax has no defined value at this point, so grosspay - grosspay * tax produces undefined results.
    3. Then we set tax. This has no effect on the value of netpay.
    4. Then we print netpay.

    Things are happening in the wrong order. You need to set variables before you use them.

    It's like you're telling someone:

    1. Read the book that's in your hand.
    2. Take The Lord of the Rings.
    3. Open it.

    And you're wondering why they're not reading from The Lord of the Rings.

提交回复
热议问题