The Char Data Type and the sizeof Operator in C

We can find out how many bytes a given type occupies by using the sizeof operator. The expression sizeof(double), for instance, will result in the number of bytes takne up by a variable of type double.

#include <stdio.h>

int main(void){
 
  printf("Variables of type char are %d bytes\n", sizeof(char));
  printf("Variables of type int are %d bytes\n", sizeof(int));
  printf("Variables of type long are %d bytes\n", sizeof(long));
 
  printf("\nVariables of type float are %d bytes\n", sizeof(float));
  printf("\nVariables of type double are %d bytes\n", sizeof(double));
 
 
  return 0;
 
}

The char type is the least memory-intensive of all the data types. Typically a char requires just 1 byte. As an unsigned type, the value stored in char can be between 0 and 255; this corresponds to the binary values 00000000 and 11111111. As a signed type, char can be between -128 and 127, due to the fact that the first bit must be used to indicate the sign.

#include <stdio.h>


int main(void){
 
  char x,y;
 
  x = 254;
  y = 127;
 
  printf("x = %d\n", x);
  printf("y = %d\n\n", y);
 
  y++;
  x++;
 
  printf("y = %d\n", y);
  printf("x = %d\n", x);
 
  return 0;
 
}

A char variable can hold any single ASCII character, so we can specify the value for a char variable with a character constant. Note that a character constant is a character written between single quotes.

#include <stdio.h>


int main(void){
 
 
  char x, y;
 
  x = 'a';
  y = 'A';
 
  printf("x = %c\t and y = %c\n", x,y);
  printf("%c = %d\t and %c = %d\n", x,x,y,y);
 
  return 0;  
 
}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s