0
#include <stdio.h>
#include <string.h>
#include "prac.h"
#define MYNAME "Butter"

int main() {
    int numberOfKids;
    int weight;
    int shirt;

    printf("If I eat a Watermelon I will weigh %d lbs \n", weight + numberOfKids+ shirt );
    return 0;
}

I compiled and ran the program and the result was 1; although I expected it to be 0. When I checked the value of each variable individually, the weight variable's value was 1. Can someone explain why that specific variables result was not 0? I am new to C and want to experiment with the basics to get a deeper understanding of the nuances of C. Any help would be appreciated.

Kyle Strand
  • 15,941
  • 8
  • 72
  • 167
  • 3
    Because variables with uninitialized values have _undefined behavior_. – Christian Dean Jan 17 '17 at 00:38
  • In other words, there is no rule to what the value of uninitialized variables must be. It could `0`, or it could be `1`, or it could be `429496729`. In short. don't rely on uninitialized variables to have a certain value. – Christian Dean Jan 17 '17 at 00:46
  • An extension to @leaf 's point. In certain scopes uninitialized variables have well defined default cases. Not all uninitialized variables are UB. – user4581301 Jan 17 '17 at 01:19
  • Yes. For example, certain static variables are initialized to zero. http://c-faq.com/decl/initval.html – bruceg Jan 17 '17 at 01:20
  • @user4581301 I didn't know that. Thanks for that correction. – Christian Dean Jan 17 '17 at 02:33

1 Answers1

6

Variables inside a function in C are not guaranteed to be set to anything by default. In memory, whatever was last stored there (which might not be flushed/erased to be 0) will be what the int is initialized to.

This is answered in Initializing variables in C

EDIT: As chux has stated below, local static variables are initialized to 0 if they aren't given an initial value. Also covered Is un-initialized integer always default to 0 in c?

Community
  • 1
  • 1
ginginsha
  • 142
  • 1
  • 11
  • Thanks for the quick reply! Ironically, I read the same thread you linked but noticed the variable was inside a function. So, I wanted to make sure the explanation applied for local variables. Thanks again for clarifying. – Jean Cabral Jan 17 '17 at 00:45
  • 1
    Hmmm: `static int x` inside a function _is_ initialized to 0. – chux - Reinstate Monica Jan 17 '17 at 00:46
  • @JeanCabral I don't want to be too harsh, because this site can sometimes be unfriendly for new users. But please recognize that for new questions, we not only expect some level of research effort, but for you to *tell us in your question* what research you've done. You do not mention in your question that you've already read the answers in that link, and honestly I cannot understand why you would write that you "expected" the variable to be initialized to 0, given the content in the linked answers. – Kyle Strand Jan 17 '17 at 01:00