DEV Community

loading...
Cover image for C - Intro To Data Types & Variables

C - Intro To Data Types & Variables

ethanmgustafson profile image Ethan Gustafson ・8 min read

Table of Contents:


I was really surprised when I began learning about variables and data types in C. After understanding what happens under the hood for those languages, I began seeing how this language influences and shapes them.

Memory

Programs need to store the memory it allocates upon runtime. In C, you are allowed to make your program as efficient as possible with how much memory you wish to allocate. Computer memory is stored in binary, 1's, and 0's. Bits are grouped together in sets of 8. A set of 8 bits is a byte.

Now, how does the computer know where to find the memory it allocates? Each set of bytes are given a unique address. A label to let the computer know where it is. The address of the byte is uniquely referenced in memory.

RAM

But where is the memory stored? In the hard drive and RAM (Random-Access-Memory). Persistent data is stored in the hard drive, while memory in RAM is temporary. It clears out when the computer shuts down. The more RAM and the speed of that RAM you have, the more efficient your program is.

Variables and Constants

One of the ways your program will allocate memory is with variables and constants. Variable and Constant names become identifiers that represent the unique address of values stored in RAM by your program. Your program uses these names to find the unique address of values in RAM.

A Constant is a type of data that doesn't change. They keep their values through the lifecycle of a program.

A Variable is a type of data that may be modified or assigned values through the lifecycle of a program.

Declaration and Initialization

If you are familiar with JavaScript, there is a concept of declaring and initializing variables. JavaScript is written in C++. You can learn what declaring and initializing actually means in C.

When you declare a variable in JavaScript, you specify which type of variable it is, followed by the variable identifier(name).

  var myName;
Enter fullscreen mode Exit fullscreen mode

If you type the above into the console of the web browser, you'll see that the variable is initialized with a value of undefined. The variable was declared, but it wasn't initialized with a specified value. JavaScript did that for you, with undefined.

Initializing literally means assigning a variable an initial value. When you first assign a value to a variable, it becomes initialized.

In JavaScript, you would commonly specify the type of variable with var, let, or const. In C, you must specify the data type of the variable.

  int myNumber = 1;
Enter fullscreen mode Exit fullscreen mode

If you declare a variable in C without initializing it, you will encounter compilation errors. C reads code top-to-bottom. Variables cannot be referenced before they are declared. It is better to declare and initialize your variables in one step.

If the compiler sees that a declared variable is referenced later without a value, it will return a compilation error. Variable names in C must begin with a letter or underscore in order to be valid.

You can also declare and/or initialize many variables of the same data type on one line:

  int ethanAge = 24, numOfBlogs = 21, randomNum = 350;
Enter fullscreen mode Exit fullscreen mode

It's a better practice to not mix declared and uninitialized variables on one line. Either write straight declared or initialized variables only.

  int ethanAge, numOfBlogs, randomNum;
Enter fullscreen mode Exit fullscreen mode

Data Types

There are many data types in C, as well as many variations of those data types. Variations of data types allow for the accuracy of use cases pertaining to memory efficiency. Data types let the compiler know just how much memory to allocate.

The amount of memory that is allocated is dependent on the type of computer you use. A data type may take up more or fewer bits on your computer.

This list will show you C data types and how much memory is allocated for each: C - Data Types

Primitive

Primitive data types are not objects. Everything in C is primitive because C isn't object-oriented. They can store a great variety of data.

You are able to specify the type of variable with a reserved keyword. These keywords are predefined by C. These keywords are called Type Specifiers.

int

int is a reserved keyword (type specifier) for the integer data type. It will only store negative, positive, or zero integers. It will not store numbers with decimal places. No commas or spaces are allowed.

  int myNumber = 250;
Enter fullscreen mode Exit fullscreen mode

int allows you to assign numbers and hexadecimal numbers. Hexadecimal numbers are Base-16:

#include <stdio.h>

int main()
{
  int hex = 0xf5d7ad;

  printf("Hex number: %d\n", hex);

  return 0;
}

// outputs: Hexa number: 16111533
Enter fullscreen mode Exit fullscreen mode

The compiler will know the value is hexadecimal by the initial 0x, followed by the actual hex number.

The amount of bytes the int data type takes up is usually 2 or 4 bytes. Its number range is -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647.

float

The float data type is reserved for decimal point numbers. These are called 'floating-point' numbers, which are just numbers containing decimal places.

They usually take up 4 bytes. Its value range is 1.2E-38 to 3.4E+38, and its precision is 6 decimal places.

#include <stdio.h>

int main()
{
  float myFloat = 120.227233;

  printf("The value of myFloat: %.2f\n", myFloat);

  return 0;
}

// outputs: The value of myFloat: 120.23
Enter fullscreen mode Exit fullscreen mode

double

The double data type is the same as float, except you are allowed to store much larger numbers within it. It takes up 8 bytes, has a number range of 2.3E-308 to 1.7E+308, and a precision of 19 decimal places.

#include <stdio.h>

int main()
{
  double myDouble = 2.223456789;

  printf("The value of myDouble: %lf\n", myDouble);

  return 0;
}

// outputs: The value of myDouble: 2.22345679
Enter fullscreen mode Exit fullscreen mode

_Bool, bool

The _Bool, bool data type is reserved for two boolean values only: True and False. A 0 is false, and a 1 is true.

The difference between _Bool and bool is syntax. With _Bool, you can only assign the value of a 1 or 0:

  _Bool myBoolean = 1; // true
  _Bool secondBoolean = 0; // false
Enter fullscreen mode Exit fullscreen mode

bool allows you to actually assign the variable values of true and false. In order to use it in your program, you have to include the <stdbool.h> header file:

#include <stdio.h>
#include <stdbool.h> 

int main()
{
  bool myBoolean = true;

  printf("The value of the myBoolean variable is: %d\n", myBoolean);

  return 0;
}

// outputs: The value of the myBoolean variable is: 1
Enter fullscreen mode Exit fullscreen mode

enum

The enum data type allows you to define your own data type for a variable. The data it can contain is defined by you. These values will be the only ones permitted within the enum.

To create an enum, type the keyword enum, followed by the identifier name, followed by curly braces.

You can set the values within the curly braces, separated by commas, with identifier names.

#include <stdio.h>

int main()
{
  enum Sports { Soccer, Baseball, Swimming, Tennis };

  return 0;
}

Enter fullscreen mode Exit fullscreen mode

To create more variables of the same enum data type, write the enum keyword followed by the same identifier name, then assign it to one of the values in the list.

The items in the curly braces are indexed, starting at zero. Soccer would have an index of 0. Printing out the results of the enum would return the number of the item in the enum.

#include <stdio.h>

int main()
{
  enum Sports { SOCCER, BASEBALL, SWIMMING, TENNIS };

  enum Sports soccer = SOCCER, baseball = BASEBALL;

  printf("\soccer value: %d\n", soccer);
  printf("\baseball value: %d\n", baseball);

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

char

The char data type is reserved for a single character. It is different from a character string. Strings in C strictly use double quotes. Characters strictly use single quotes.

#include <stdio.h>

int main()
{
  char letterOfMyFirstName = 'E';

  printf("What is the letter of my first name? %c\n", letterOfMyFirstName);
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Other Type Specifiers

There are three keywords that allow you to modify the amount of memory allocated to type int and in one case, a double: short, long, and unsigned.

short

The short specifier is used to decrease the number of bytes the int type will take up. It will ensure the int only takes up 2 bytes. It can either be used by itself, or with the int keyword:

#include <stdio.h>

int main()
{
  short myShortInteger = 10;
  short int secondShortInteger = 5;

  printf("myShortInteger: %d, secondShortInteger: %d\n", myShortInteger, secondShortInteger);
  return 0;
}

// outputs: myShortInteger: 10, secondShortInteger: 5
Enter fullscreen mode Exit fullscreen mode

long

The long specifier is used to increase the number of bytes a variable of type int or double will take up. For int, it will take 8 bytes or (4bytes for 32 bit OS). For double, it will take 10 bytes.

#include <stdio.h>

int main()
{
  long int longerInt = 9223372036854;
  long double longerDouble = 4.9406564584124654;

  printf("longerInt: %ld, longerDouble: %Lf\n", longerInt, longerDouble);
  return 0;
}
// outputs: longerInt: 9223372036854, longerDouble: 4.940656
Enter fullscreen mode Exit fullscreen mode

long long

The long specifier is used to almost doubly increase the number of bytes a variable will take up. It takes up 8 bytes.

#include <stdio.h>

int main()
{
  long long int longerLongerInt = 9223372036854775807;

  printf("longerLongerInt: %lli\n", longerLongerInt);
  return 0;
}
// outputs: longerLongerInt: 9223372036854775807
Enter fullscreen mode Exit fullscreen mode

signed

The signed specifier isn't necessary to use, but it can make your semantic meaning of a variable to be explicit. It specifies that a variable will have a value of zero, positive or negative number.

#include <stdio.h>

int main()
{
  signed int negativeNum = -10;
  signed short int smallerInt = 4;
  /* is the same as:

  int negativeNum = -10;
  short int smallerInt = 4;

  */ 

  printf("negativeNum: %d, smallerInt: %d\n", negativeNum, smallerInt);

  return 0;
}
// outputs: negativeNum: -10, smallerInt: 4
Enter fullscreen mode Exit fullscreen mode

unsigned

The unsigned specifier specifies that the variable will only contain positive values.

#include <stdio.h>

int main()
{
  unsigned short int positiveShortNumber = 5;

  printf("positiveShortNumber: %d\n", positiveShortNumber);

  return 0;
}
// outputs: positiveShortNumber: 5
Enter fullscreen mode Exit fullscreen mode

Final Note: Format Specifiers and the printf() Function

The printf() statement above in all the examples will output text to standard out (stdout). In order to use variable arguments to the printf() function, you must translate what the data type of the variable arguments are.

Format specifiers will be used to display variables as output. They begin with the percent symbol (%), followed by an argument specifying a data type. %d specifies that a variable will be of type int.

Read more on the printf() function, data types, escape characters, format specifiers and the standard input/output stream below. Thank you for reading!

Resources:

Discussion (0)

pic
Editor guide