Saturday, July 18, 2020

Exploring integer data type in C

Points to be known:
  • An integer data is one among the basic data types in C language. 
  • By default all the integer in C are signed.
  • For using unsigned we must use unsigned int keyword.
  • Size of the integer may be 2 byte or 4 byte, it is purely compile dependent.
  • short is a qualifier which makes the size of integer 2 or 4 bytes.
  • long is also a qualifier which makes the size of the integer data type 8 byte.
  • The following picture depicts what will happen when the value of the integer variable exceeds its range. Roll over happens whenever the value exceeds the range. 
  • In the below diagram a 2 byte signed integer's roll over is shown.
                                      
  • In case of Unsigned int the value ranges from 0 to 65,536 for 4 byte and 0 to 32,767 for 2 byte int.
Examples:
Consider the following example,

#include<stdio.h>
int main()
{
int a = 5;
float b = 10.5;
printf("%f",a+b);
return 0;
}

Here the output will be 15.500000 because float variable has higher precedence than int variable.

Consider the same example

#include<stdio.h>
int main()
{
int a = 5;
float b = 10.5;
printf("%d",a+b);
return 0;
}

If we try to print the integer part of this expression, the output will be 0 here. Because when an int variable is added with float, the resulting value always will be float for the above mentioned reason.

Again consider the same example with slight modification,

#include<stdio.h>
int main()
{
int a = 5;
char b = 'a';
printf("%d",a+b);
return 0;
}

Here the output will be 102, because the ASCII value of the character will be added and %d is the format specifier so it will print the integer value of the expression.

Extras:
  • Both %d and %i can to used as format specifier for integer in C.
  • %5d will print the integer value after 5 spaces before it.
For more examples follow our Instagram page

Learnclang


No comments:

Post a Comment

Exploring float data type in C

Float is one among the basic data type in C.  Floating point numbers in C has precision up to 6 decimal places.  T he header file float.h de...