Datatypes in C++

Data types are used to classify and define variables in programming languages. They determine the range of values a variable can hold and the operations that can be performed on it.

Built-in Primitive Data Types

C++ provides several built-in primitive data types, including integers, floating-point numbers, characters, booleans, and void.

Example
#include<iostream>
int main() 
{
  // Built-in Primitive Data Types
  int myInteger = 42;          // Integer data type
  float myFloat = 3.14;        // Floating-point data type
  char myCharacter = 'A';      // Character data type
  bool myBoolean = true;       // Boolean data type
  void myVoid;                 // Void data type
  // Output
  std::cout << "myInteger: " << myInteger << std::endl;
  std::cout << "myFloat: " << myFloat << std::endl;
  std::cout << "myCharacter: " << myCharacter << std::endl;
  std::cout << "myBoolean: " << myBoolean << std::endl;
  return 0;
}

Modifiers for Data Types

C++ supports various modifiers that can be applied to data types to alter their behavior, such as signed, unsigned, short, long, and const.

Example
#include<iostream>
int main() 
{
   unsigned int positiveInteger = 123;  // Unsigned integer
   short int smallInteger = 10;         // Short integer
   long int largeInteger = 1000000;     // Long integer
   const float pi = 3.14159;            // Constant float
   // Output
   std::cout << "positiveInteger: " << positiveInteger << std::endl;
   std::cout << "smallInteger: " << smallInteger << std::endl;
   std::cout << "largeInteger: " << largeInteger << std::endl;
   std::cout << "pi: " << pi << std::endl;
   return 0;
}

User-Defined Data Types

C++ allows programmers to define their own data types using classes and structures. These user-defined types provide a way to encapsulate data and associated functions.

Example
class Rectangle {
  int width;
  int height;
public:
  void setDimensions(int w, int h) {
    width = w;
    height = h;
  }
};
struct Point {
  int x;
  int y;
};

Type Inference

C++ supports type inference through the auto keyword, allowing the compiler to deduce the data type based on the assigned value.

Example
auto myVariable = 42;    // Compiler deduces myVariable as an integer
auto myValue = 3.14;     // Compiler deduces myValue as a double

Sizeof Operator

The sizeof operator is used to determine the size of a data type or a variable in bytes.

Example
int sizeOfInt = sizeof(int);        // Size of int data type
int sizeOfVariable = sizeof(myVariable);  // Size of variable myVariable

Summary

Data types in C++ are essential for defining variables and specifying the kind of data they can hold. C++ provides built-in primitive data types, modifiers, and the ability to define user-defined data types. Understanding data types and their modifiers is crucial for writing reliable and efficient code.