Main Content

Defining, declaring and initialising variables in C

Archive - Originally posted on "The Horse's Mouth" - 2012-01-24 23:34:11 - Graham Ellis

When you declare a variable in C, you're instructing the compiler to set memory aside for it, and you're also telling the compiler how to handle any references to that memory.

• C does NOT spend time working out what sort of data you're storing and how many bytes are needed - it's up to you to tell it the right data sort and to make sure you handle it in the right way (though some checks and warnings are made for you at compile time)
• C does NOT spend time setting initial values into all the variables that you declare - it's up to you to initialise variables if it's needed within your application.

If you get these things wrong, you'll end up treating the bit pattern of an integer as if it's a float, or making use of whatever happened to be left in my ory from the last program during the running of your program, with results which will be unpredictable.

Example ([full source]) - with declarations without initialisation, I may get:

  int fred;
  float boat;


  munchkin:c12 grahamellis$ ./vars
  Integer is 32767; float is 27679303629726023680.000000
  munchkin:c12 grahamellis$


But with declarations with initialisations from the same program ([full source]) , I will get:

  int fred = 15;
  float boat = 17.778;


  munchkin:c12 grahamellis$ ./vars2
  Integer is 15; float is 17.778000
  munchkin:c12 grahamellis$


It is features like this, of C that make it a very fast language to run, but a very much longer-winded language in which to design and write code as there's so much more work you have to do to make sure things that other languages would check don't get overlooked. Just one of the reasons that C is great for the really heavy compute jobs, and for code that's copied millions of times like operating systems, but is a poor choice for lighter work and occasional code!