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.

5
  • 3
    Because variables with uninitialized values have undefined behavior. Jan 17, 2017 at 0: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. Jan 17, 2017 at 0:46
  • An extension to @leaf 's point. In certain scopes uninitialized variables have well defined default cases. Not all uninitialized variables are UB. Jan 17, 2017 at 1:19
  • Yes. For example, certain static variables are initialized to zero. c-faq.com/decl/initval.html
    – bruceg
    Jan 17, 2017 at 1:20
  • @user4581301 I didn't know that. Thanks for that correction. Jan 17, 2017 at 2:33

1 Answer 1

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?

3
  • 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. Jan 17, 2017 at 0:45
  • 1
    Hmmm: static int x inside a function is initialized to 0. Jan 17, 2017 at 0: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. Jan 17, 2017 at 1:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.