What are primitive data types in C++?
What is a variable?
Variables are a fundamental part of programming. In C++, a data type is used to declare or define each variable. For instance, if a variable can hold integers or if it can also store other symbols.
Primitive data types
The following data types are frequently used in C++:
-
int: This is used to store integer values such as1,-1,7, etc.int i = 5; -
floatanddouble: Both these data types store floating point values such as1.56,2.87,-4.7, etc. The difference between these two data types is the size. We can store up to 8 bytes in adoublevariable while only 4 in afloatvariable.float f = 5.65; double d = 7.8987; -
bool: This is used to store two states:true/1orfalse/0. If we want to store a number with a more significant value, our choice would bedouble.bool b = true; // or we can also declare bool as this bool b = 0; -
char: This is used to store a single character value such asa,A,#, etc.char c = 'A'; -
string: This is used to store text such asWelcome to Educative,@Answers, etc.string s = "This is a string";
Except for the last data type, “string,” which is only accessible in the string library, all the data types mentioned above are available in the iostream library. String usage requires adding #include <string> at the beginning of the code.
Example
The following code demonstrates the usage of the data types mentioned above.
#include <iostream>#include <string>using namespace std;int main(){int number = 5;float decimal1 = 5.87;double decimal2 = 87.0987;bool state1 = true;bool state2 = 0;char letter = 'A';string text = "Welcome to Educative";cout << "The integer value is: " << number << endl;cout << "The float value is: " << decimal1 << endl;cout << "The double value is: " << decimal2 << endl;cout << "We can write boolean value in two forms as: " << state1 << " and " << state2 << endl;cout << "The character value is: " << letter << endl;cout << "The string value is: " << text << endl;return 0;}
Explanation
- Line 2: We’ll add
#include <string>library for usingstring. - Line 7: Initialize an
intvariablenumberand assign a value of5. - Line 8: Initialize a
floatvariabledecimal1and assign a value of5.87. - Line 9: Initialize a
doublevariabledecimal2and assign a value of87.0987. - Line 10–11: Initialize a
boolvariablestate1andstate2and assign a valuetrueand0, respectively. Another way to assign value to a bool is to assign0/1to the variable. But when we print the value ofstate1it prints1, nottrue. - Line 12: Initialize a
charvariableletterand assign a valueA. - Line 13: Initialize a
stringvariabletextand assign aWelcome to Educativevalue. - Line 15–20: Displaying the values of variables by prompting a message.
Free Resources