Welcome to this comprehensive guide on C++ data types! In this lesson, we'll explore the various types available in C++, their uses, and practical examples to help you understand them better. Let's get started!
Data types are a way to categorize variables according to the type of data they hold. In C++, we have several built-in data types:
int: Integersfloat: Floating-point numbersdouble: Double precision floating-point numberschar: Charactersbool: Boolean (true or false)string: Strings (not a built-in type, but we'll discuss it anyway)An int is used to store whole numbers, both positive and negative. The size of an int varies depending on the system you're working on.
#include <iostream>
int main() {
int myNumber = 10;
std::cout << "The value of myNumber is: " << myNumber << std::endl;
return 0;
}š” Pro Tip: To print the value of a variable, we use the std::cout function and the stream insertion operator <<.
float and double are used to store real numbers with decimal points. double provides more precision than float.
#include <iostream>
int main() {
float myFloat = 3.14f;
double myDouble = 3.14159265358979323846;
std::cout << "The value of myFloat is: " << myFloat << std::endl;
std::cout << "The value of myDouble is: " << myDouble << std::endl;
return 0;
}A char is used to store individual characters. In C++, each character is represented by its ASCII value.
#include <iostream>
int main() {
char myCharacter = 'A';
std::cout << "The value of myCharacter is: " << myCharacter << std::endl;
return 0;
}bool is used to store logical values: true or false.
#include <iostream>
int main() {
bool isTrue = true;
bool isFalse = false;
std::cout << "The value of isTrue is: " << isTrue << std::endl;
std::cout << "The value of isFalse is: " << isFalse << std::endl;
return 0;
}Though C++ does not have a built-in string data type, we can still work with strings using the string library.
#include <string>
#include <iostream>
int main() {
std::string myString = "Hello, World!";
std::cout << "The value of myString is: " << myString << std::endl;
return 0;
}What is the output of the following code?
That's it for this part! In the next lesson, we'll dive deeper into C++ data types and explore more complex concepts. Stay tuned! š