Fellas, why is this happening, especially sometimes but not other times?

Here, I run the program three times, getting the exact same correct output. On the fourth, it outputs broken numbers. The function prnStats what’s being executed.

  • @nachtigall@feddit.de
    link
    fedilink
    3
    edit-2
    1 year ago

    In prnStats() you do not initialise all values. The following snippet only initialises Calories = 0, the rest remains uninitialised.

     float C,F,P,L,Calories = 0;
    // is the same as
    float C;
    float F;
    float P;
    float L;
    float Calories = 0;
    

    Try this instead:

     float C,F,P,L,Calories;
    C = F = P = L = Calories = 0.0;
    

    I can’t recommend -fanalyzer option enough for finding this kind of mistakes :)

    • @lofenyy@lemmy.caOP
      link
      fedilink
      21 year ago

      Awesome, thank you so much!

      How do you use fanalyzer? I’m passing it as a build option in GCC, assuming that it’ll alert me of any issues on either compile or runtime.

      • @nachtigall@feddit.de
        link
        fedilink
        2
        edit-2
        1 year ago

        Exactly! just pass it as an argument to GCC and it will perform static analysis of the code at compile time. For example, with the code you provided, the output looks like this.