Char

From Valve Developer Community
Revision as of 09:35, 11 August 2005 by InvaderZim (talk | contribs) (added error descriptions)
Jump to navigation Jump to search

A character is, programmatically, one ASCII number value used to represent a keyboard character('a', 'x', '1', '6', 'ê'). This variable is declared by the name char, and its value must be surrounded by apostrophes:

      //Either case will end compilation
   char anA = A;  //Wrong     Compiler Says: "Cannot convert from unknown type to char"   Error
   char anA = "A";  //Wrong   Compiler Says: "Cannot convert from const char[2] to char"    Error
   char anA = 'A';  //Correct 
   

Note: If you are familiar with arrays, the second error should look odd to you! "A" is a const char[2]?

     See strings for more info! 

At its core, a char is really just an 8-bit integer, its value ranging from 0 to 255 In fact, if you require a integer to store a very small value, a character can be used for this purpose, but it is important to remember that if you wish to use a char for this purpose that they are by definition unsigned:

   char smallInteger = 127;  //Ok!
   char smallInteger = -23;  //Wrong   Compiler Says: "Signed/unsigned mismatch, possible loss of data"  Warning
      //In this case smallInteger will be set as 23

However, a different keyword, signed may be applied to it in order to allow negative values to be stored, but the greatest absolute value it can hold will be cut in half.

   signed char smallInteger = 238; //Wrong  Compiler Says "Truncation of constant value" Warning
      //In this case smallInteger will be set as (2^7)-1, the largest value possible
   signed char smallInteger = 72;  //Ok!
   signed char smallInteger = -96; //Ok!

This is why when assigning a char an ASCII number value you must use apostrophes, so that the compiler know to convert that keyboard character into its 8-bit ASCII value.

Strings are arrays of, or pointers to Characters. These are used more often than characters are in the Source Engine.