2c-Data Types 1
2c-Data Types 1
char a single byte character. int an integer number usually 4 bytes. float a single precision real number usually 4 bytes. double a double precision real number usually 8 bytes.
char
int
float
double
Data types in C
short int (or just short) an integer number, usually 2 bytes. long int (or just long) an integer number, 4 or 8 bytes. unsigned vs. signed
For example, unsigned chars can range from 0 to 255 while (signed) chars range from -128 to 127.
To declare a variable as unsigned, add the unsigned keyword before its type. For example unsigned int ui;
Memory allocation
Letters. Digits. Keyboard signs. Non-printable characters. But also small numbers (0 to 255 or -128 to 127).
Text as numbers
Every character is assigned a numeric code. There are different sets of codes:
ASCII (American Standard Code for Information Interchange) most common. Maybe others.
Most of the time, you don't care what the particular numbers are. The table above shows only 128 characters (7 bits). Some are non-printable. Extended ASCII code contains 256 characters.
Note contiguous sets of numbers, upper case and lower case characters.
An example
Example of char as both a character and a small number
#include <stdio.h> int main() { char i = 'b'; printf("i as a character is %c\n", i); printf("i as an integer is %d\n", i); printf("The character after %c is %c\n", i, i + 1); return 0; }
Another example
/* Get the position of a letter in the abc */ #include <stdio.h> int main() { char letter; printf("Please enter a lowercase letter\n"); scanf("%c", &letter); printf("The position of this letter in the abc is %d\n", letter - 'a' + 1); return 0; }
Exercise
Write a program that accepts as input
and outputs
Solution
/* Convert a letter to uppercase */ #include <stdio.h>
int main() { char letter; printf("Please enter a lowercase letter\n"); scanf("%c", &letter); printf("This letter in uppercase is %c\n", letter - 'a' + 'A');
return 0; }
Overflow
Happens when a variable gets assigned a value that is outside of its range
This is equivalent to saying that the number of bits required to encode the value exceeds the number of bits in the variable
The value of the variable will usually be non-sense
Overflow An example
#include <stdio.h> int main() { int iA = 1000; int iB = 1000000; int iC = 3000000; int iD = 5000000; printf ("%d * %d = printf ("%d * %d = printf ("%d * %d = printf ("%d * %d = return 0; }