Pages

Thursday, September 14, 2017

Easy tutorial for C / C++ Data type


Easy tutorial for C / C++ Data type

What is a datatype?

- Program source code consists of variables, constants and reserved words. Each data is available in its own format and is called a data type.

(Example: Assume you declare a variable named Num. If you want to store a number (an integer) in this variable, you can declare the variable Num as an integer type to get the right result.)

- Before summarizing the data types, the concepts of constants and variables in C language are summarized as follows.

Constant : 

- Normally in mathematics, a constant is used to describe a "number" that does not change. In programming, not only numbers but also characters are included in constants. In other words, it means fixed value without changing. (E.g., 1, 2, 3, ..., +, -, ...)

Variable : 

- Variable means a value that changes to a concept opposite to a constant. In the above example, Num corresponds to the variable. 3 is substituted for Num (Num = 3;), this Num is used as 3 in the program.



*Tip: Here is a simple rule to know about creating variable names:

- Consist of uppercase and lowercase letters, Arabic numerals, and underscores (_).
- Case sensitive.
- The first letter begins with an underscore (_) or alphabetical case.
- Do not use reserved words (names that have already been reserved for use in the C ++ language, such as int, double, for, and while).


Integer constant :

- There are unsigned short, (unsigned) int, and (unsigned) long data types that are used to represent numbers without a decimal point. The reason for distinction is to give slightly different sizes when storing values in storage space. 

- If you put unsigned in front, it means you will treat only positive numbers. In my case, I did not have much use for other things than the (unsigned) int.


Example usage : int num = 7 ;


Double constant :

- The datatype used to represent a decimal number is float and double. In my case, I use a double rather than a float. It's convenient in many ways ...


Example usage : double num = 7.1 ;


Character constant :

- The type of data that literally represents a character, such as a single character, a string constant, and so on. Use a (unsigned) char for single characters, or a string for strings.


Example usage : char CH = 'T' ; string STR = "TTTTT" ;


*Tip: Here is a simple code to check the size of the data types on my computer system:

#include <iostream>
using namespace std;
int main() {
cout<< "Size of int = " << sizeof(int) << " byte(s)"<<endl;
cout << "Size of double = "<<sizeof(double)<<" byte(s)"<<endl;
cout<< "Size of char = " << sizeof(char) << " byte(s)"<<endl;
return 0;
}

The results below are from my computer system.

Size of int = 4 byte(s)
Size of double = 8 byte(s)
Size of char = 1 byte(s)

No comments:

Post a Comment