Variables, Data Types, and Operators in
C/C++
1. Compilers and Interpreters
- A **compiler** translates the entire source code into machine code before execution.
Example: C, C++ use compilers.
- An **interpreter** translates and runs code line-by-line. Example: Python uses an
interpreter.
Example (C++ Compiler - g++):
$ g++ [Link] -o program
$ ./program
2. Data Types
- **int**: Used for integers (e.g., 1, -100, 45)
- **float**: Used for small decimal numbers (e.g., 3.14)
- **double**: Used for large decimal numbers (e.g., 123.456789)
- **char**: Used for single characters (e.g., 'A', 'z')
- **string**: Used for text (C++ string class)
- **bool**: Used for Boolean values (true or false)
Example:
int age = 25;
float pi = 3.14f;
double distance = 123456.789;
char grade = 'A';
string name = "Alice";
bool passed = true;
3. Variables and Constants
- **Variable**: A named space in memory to store data.
- **Constant**: A value that cannot be changed once assigned.
Example:
int x = 10; // variable
const float PI = 3.14159; // constant
4. Type Conversion
- **Implicit Conversion**: Automatically done by compiler.
- **Explicit Conversion** (Type Casting): Done manually by the programmer.
Example (Implicit):
int a = 10;
float b = a; // int is converted to float
Example (Explicit):
float x = 10.5;
int y = (int)x; // float is cast to int (value becomes 10)
5. Operators in C/C++
A. **Arithmetic Operators**: +, -, *, /, %
Example:
int sum = 10 + 5; // 15
B. **Relational Operators**: ==, !=, >, <, >=, <=
Example:
if (a > b) { ... }
C. **Logical Operators**: && (AND), || (OR), ! (NOT)
Example:
if (a > 0 && b > 0) { ... }
D. **Assignment Operators**: =, +=, -=, *=, /=, %=
Example:
x += 5; // same as x = x + 5;
E. **Bitwise Operators**: &, |, ^, ~, <<, >>
Example:
int a = 5; // 0101
int b = 3; // 0011
int result = a & b; // result is 1 (0001)