C Variables

  1. Comments
  2. Variables
  3. Constants
  4. Arrays
  5. enums

Since we know how to use printf() to write output we can start looking at the rest of the C Language.

Comments

Comments, like in Java, come in two forms. Block comments and rest of the line comments

Block Comments

/* Block comments begin with slash asterisk
   and keep going
   until you reach an asterisk slash */

To End Of Line Comments

printf("Hello World"); // Comments from // to end of line

Variables

Variables are going to look very familiar to variables in Java. We’ve already used a couple of different variables, we’re going to cover the basics of how variables are used and look at some more advanced features that will come in useful later on.

Types

Variable Type Descriptiop
char a byte holding a single character
int integer
float single precision floating point number
double double precision floating point number
bool single boolean value (see Boolean section below)
void represents the absence of type

These are the basic variables, the equivalent of Java’s primitives. We can create more types and we will do that later on.

Note that there is no string variable. C does not have a string variable at all. Instead C uses arrays of characters. We will look at arrays soon and using arrays of characters as strings for later on.

Defining Variables

Again this is very similar to Java. We define variables by type and can initialise them immeadiately or later.

int    i, j, k;
char   c, ch;
float  f, salary;
double d;
int d = 3, f = 5;           // definition and initializing d and f. 
byte z = 22;                // definition and initializes z. 
char x = 'x';               // the variable x has the value 'x'.

extern Declaration

The extern keyword can be used to declare that a variable will exist without actually creating it. We don’t do this often but sometimes it is useful to let the compiler know that a variable will be created at some point and not to worry about it for the time being. The C compiler does not look ahead to see if something exists, it it doesn’t know what something is when it compiles a line of code it will fall over.

#include <stdio.h>

// Variable declaration but not creation
extern int a, b;
extern int c;
extern float f;

int main () 
{
  // variable definition: (creation but not initialisation)

  int a, b;
  int c;
  float f;

  /* actual initialisation */
  a = 10;
  b = 20;

  c = a + b;
  printf("value of c : %d \n", c);

  f = 70.0/3.0;
  printf("value of f : %f \n", f);

  return 0;
}

This also applies to functions. The code below will fail

int main() {

   // function call
   int i = func();
}

// function definition
int func() {
   return 0;
}

because func() is defined later in the code than the call to func() in main(). To make this work we do the following

// function declaration
int func();

int main() {

   // function call
   int i = func();
}

// function definition
int func() {
   return 0;
}

Constants

There are two methods of creating constants.

  • #define
  • const

#define

#define is used to create a constant as shown below.

#include <stdio.h>

#define LENGTH 10   
#define WIDTH  5
#define NEWLINE '\n'

int main() {
   int area;  
  
   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);

   return 0;
}

const

const is used to create variables that are constant as below.

#include <stdio.h>

int main() {
   const int  LENGTH = 10;
   const int  WIDTH = 5;
   const char NEWLINE = '\n';
   int area;  
   
   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);

   return 0;
}

The difference between the two is scope. In the second example the constants only exist in main(), in the first they exist everywhere. It is standard practice to name constants in UPPERCASE so they are easily distinguished from variables.

static Variables

The static keyword can be used to extend the life of variables beyond their normal scope.

A static variable declared outside of a function is a global variable that will maintain its value throughout the lifetime of the application and can be used anywhere in the code. A static variable declared inside a function exists only in that function but its value is remembered between function calls.

#include <stdio.h>
 
/* function declaration */
void func(void);
 
static int count = 5; /* global variable */
 
main() {

   while(count--) {
      func();
   }
	
   return 0;
}

/* function definition */
void func( void ) {

   static int i = 5; // local static variable
   /* i is create when the function is first called and initialised to 5
      When func() exits the current value of i is remembered
      When func() is called again, i is not created and initialised, 
      instead its previous value is remembered */
   i++;

   printf("i is %d and count is %d\n", i, count);
}

Gives the following output.

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

Global variables are considered bad programming practice. If a problem occurs due to a global variable it can be very difficult to track the bug down since the global variable can be changed anywhere. They are, however, sometimes the easiest solution to a problem.

Arrays

int x[10];

for (int i=0; i<10; i++)
{
   x[i] = i;
}

Array Initialisation

As with other declarations, array declarations can include an optional initialization. Arrays are initialized with a list of values The list is enclosed in curly braces.

int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};

The number of initializers cannot be more than the number of elements in the array but it can be less, in which case the remaining elements are initialized to 0. The array size can be inferred from the number of initializers by leaving the square brackets empty so these are identical declarations:

int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16};
int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16};

Global Variables

C allows for global variables. These are declared a the top of the file and are accessible throughout the code.

int i=4;          /* Global definition   */

main()
{
      i++;          /* Global variable     */
      func();
      printf( "Value of i = %d -- main function\n", i );
}

Where the same variable name is used for local and global variables the local variable takes precedence, it is the local variable that is used.

int i=4;          /* Global definition   */

main()
{
      i++;          /* Global variable     */
      func();
      printf( "Value of i = %d -- main function\n", i );
}

func()
{
      int i=10;     /* Local definition */
      i++;          /* Local variable    */
      printf( "Value of i = %d -- func() function\n", i );
}
This will produce following result
Value of i = 11 -- func() function
Value of i = 5 -- main function

The enum Data Type

An enum is is an enumerated data type.

Defining an enum

enum months { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}

This will set values to each item in the list, starting at zero.

JAN = 0, FEB = 1, MAR = 2, .. NOV = 10, DEC = 11

We can override any of these values. The values do not need to be unique.

enum months { JAN=1, FEB=2, MAR=9, APR=5, MAY=11, JUN=12, JUL=4, AUG=3, SEP=8, OCT=5, NOV=1, DEC=2}

Any entries not given a value will be assigned one, starting at one greater than the last value used or zero if none have been.

enum months { JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}

will result in the months being numbered

JAN = 1, FEB = 2, ... DEC = 12

Using an enum

The keywords in the enum can then be used as replacements for the numbers they are associated with in the code.

enum months { JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}

int i = JAN;

sets i equal to 1.

Using enums as a data type

enums are most useful when used as a data type, creating a new type of variable.

enum months { JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}

enum months current_month;
current_month = SEP;

In the example above ``current_month` can only be set to one of the value in the definition (e.g. FEB or one of the numerical values).