Jump to content

int x and int x=0 difference?


Jay001

Recommended Posts

don't understand why we should set up the variable to be 0?
 
public static void main(String[] args) {
        String recipeName, userInputStr;
        int userInputInt;
        int numberOfServings = 0;
        double totalCalories = 0;
        double totalFat = 0;
        double totalCholesterol = 0;
        double totalCarbohydrate = 0;
        double totalProtein = 0;

        Scanner inputStream = new Scanner(System.in);
        System.out.println(" name of this recipe? ");
        recipeName = inputStream.nextLine();
        System.out.println(" How many servings? ");
        userInputStr = inputStream.nextLine();
        numberOfServings = Integer.parseInt(userInputStr);
        if (numberOfServings < SERVINGS_MIN || numberOfServings > SERVINGS_MAX) {
            System.out.println(" Wrong number of servings.");
            System.exit(-1);
        }
        System.out.println("----------List of Possible Ingridients==========");
        System.out.println(INDENT + "Food #1: " + FOOD_1_NAME);
        System.out.println(INDENT + "Food #2: " + FOOD_2_NAME);
        System.out.println(INDENT + "Food #3: " + FOOD_3_NAME);
        System.out.println(INDENT + "Food #4: " + FOOD_4_NAME);
        System.out.println(INDENT + "Food #5: " + FOOD_5_NAME);
        System.out.println(" How many grams of " + FOOD_1_NAME + "? ");
        userInputStr = inputStream.nextLine();
        userInputInt = Integer.parseInt(userInputStr);
        if (userInputInt < GRAMS_MIN || userInputInt > GRAMS_MAX) {
            System.out.println(" Wrong number of grams.");
            System.exit(-1);
        }
        totalCalories += userInputInt * (FOOD_1_CALORIES_P100G / 100.);
        totalFat += userInputInt * (FOOD_1_FAT_P100G / 100.);
        totalCholesterol += userInputInt * (FOOD_1_CHOLESTEROL_P100G / 100.);
        totalCarbohydrate += userInputInt * (FOOD_1_CARBOHYDRYTE_P100G / 100.);
        totalProtein += userInputInt * (FOOD_1_PROTEIN_P100G / 100.);
Link to comment
Share on other sites

45 minutes ago, Jay001 said:

don't understand why we should set up the variable to be 0?

Function's local variables are allocated dynamically on the CPU stack. Stack is filled by functions, which allocates/frees this space, and can contain trash (undetermined data). If you have declaration of variable int x; it's uninitialized variable, its value can be random value. But later there is used operator +=. It's taking current value of variable (if it's initialized to 0, result is predictable), and adds to it something else.

There are special debugging tools which are trashing stack and newly allocated memory on purpose, to find errors caused by using of uninitialized data. These are very hard to find errors.

new operator in C++ does not clear memory of object prior calling constructor. Programmer has to do it by himself/herself in each constructor (there can be default constructor, constructor with parameters, copy-constructor etc. etc. in each of them the all object members must be manually initialized. It's easy to make mistake while adding yet another member in complex class).

ps. Even if specific language initializes variables (e.g. clears them), it's good habit to clear them by yourself. One language can allow it, other one will not.

Edited by Sensei
Link to comment
Share on other sites

26 minutes ago, Jay001 said:

I don't understand why we should use +=  because the variable is 0

In this particular case, you don't have to. You can leave variables uninitialized during declaration, and then use operator =, instead of operator +=.

But you must understand and comply to what is said in above post about uninitialized and initialized variables. Otherwise you will have unexpected random crashes in C/C++. It is very difficult to trace them.

 

 

Edited by Sensei
Link to comment
Share on other sites

43 minutes ago, Jay001 said:

so if I set up int x=0 it is using the current value to calculate?

I don't understand why we should use +=  because the variable is 0

In this particular example, you could just something like:

totalCalories = userInputInt * (FOOD_1_CALORIES_P100G / 100.);

And not initialise the value of totalCalories to zero.

The += operator is normally used in a loop. So, if you were getting several different inputs from the user:

while ... {
  userInutInt = ...
  totalCalories += userInputInt * (FOOD_1_CALORIES_P100G / 100.);
}

This would sum all the inputs into totalCalories. In this case you must initialise it to zero.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.