What does an int initialize to by default in C?

  • Mars
  • Graduate
  • Graduate
  • User avatar
  • Posts: 160
  • Loc: Flordia

Post 3+ Months Ago

Code: [ Select ]
1 #include <stdio.h>
2 main() {
3     int score;
4     printf("score=%d\n",score);
5 }
//outputs 4096
  1. 1 #include <stdio.h>
  2. 2 main() {
  3. 3     int score;
  4. 4     printf("score=%d\n",score);
  5. 5 }
  6. //outputs 4096


Not too familiar with c, but why does this print 4096? My naivete thinking would tell me that it would default to null. The only think I can think of is that 1024*4 = 4096. Maybe that has something to do with it. idk, I'm lost. I know in php which is what I'm most familiar with, int's initialize to null.

*shrug. Could somebody shed some light? Thanks.
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6254
  • Loc: Seattle, WA

Post 3+ Months Ago

The particular result is platform dependent, but the behavior is undefined. Basically, the value could be any valid integer when it's initialized, it just depends on what was previously in that location in memory.

For example, when I compile the code with gcc on my machine, I get -135926644 as an initial value.
  • Mars
  • Graduate
  • Graduate
  • User avatar
  • Posts: 160
  • Loc: Flordia

Post 3+ Months Ago

Ok, cool makes sense. Is there a particular implementation reason for that? Is the overhead for initializing it to null too expensive, or is it just that it was never put in the standardization for whatever reason?
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6254
  • Loc: Seattle, WA

Post 3+ Months Ago

C is a low level language, thus the compiler isn't going to do anything that isn't necessary. C doesn't hold your hand ;)

Some compilers may initialize the variable for you, but no, it's not in the standard, so if you're writing clean, cross-platform ANSI C, then you shouldn't expect it to.
  • dark_lord
  • Graduate
  • Graduate
  • User avatar
  • Posts: 162
  • Loc: India-Kolkata

Post 3+ Months Ago

What i had learn is, garbage value is initialized

Maybe Spork is right in explaining that. I never wondered what type of garbage value :D

Post Information

  • Total Posts in this topic: 5 posts
  • Users browsing this forum: No registered users and 76 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.