> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/07.-type-conversion.md).

# 07. Type Conversion

Type conversion means changing a value from one data type to another — like turning an `int` into a `double`, or a `double` into an `int`.

There are two kinds:

1. **Implicit conversion** — the compiler does it automatically.
2. **Explicit conversion (casting)** — you tell the compiler to do it.

***

### 1. Implicit Conversion (automatic)

The compiler converts types on its own when it's "safe" or expected — usually when mixing types in an expression.

```cpp
#include <iostream>

int main() {
    int a = 5;
    double b = 2.5;

    double result = a + b; // int 'a' is auto-converted to double
    std::cout << result << '\n'; // 7.5

    return 0;
}
```

**A common trap** — assigning a `double` to an `int` truncates (chops off) the decimal, it doesn't round:

```cpp
#include <iostream>

int main() {
    double price = 9.99;
    int wholePrice = price; // implicit conversion, decimal is DROPPED

    std::cout << wholePrice << '\n'; // 9, not 10

    return 0;
}
```

***

### 2. Explicit Conversion (casting)

You force the conversion yourself using a **cast**. This is clearer and safer because it shows *you* intended the conversion, not the compiler guessing.

#### `static_cast` (the modern, recommended way)

```cpp
#include <iostream>

int main() {
    int a = 7;
    int b = 2;

    double result = static_cast<double>(a) / b; // cast a to double first
    std::cout << result << '\n'; // 3.5

    return 0;
}
```

#### C-style cast (older style, still seen a lot, but less safe)

```cpp
#include <iostream>

int main() {
    int a = 7;
    int b = 2;

    double result = (double)a / b; // works, but static_cast is preferred in modern C++
    std::cout << result << '\n'; // 3.5

    return 0;
}
```

**Why prefer `static_cast` over C-style casts?**

* It's more visible/searchable in code (`(double)` blends in easily; `static_cast<double>` stands out).
* It only allows "reasonable" conversions — the compiler catches more mistakes for you.

***

### More cool examples

#### 1. `char` and `int` conversion (characters are just numbers under the hood)

```cpp
#include <iostream>

int main() {
    char letter = 'A';
    int code = letter; // implicit: char converts to its ASCII value

    std::cout << code << '\n'; // 65

    char back = static_cast<char>(66);
    std::cout << back << '\n'; // B

    return 0;
}
```

#### 2. `bool` conversions

```cpp
#include <iostream>

int main() {
    bool isReady = true;
    int value = isReady; // true becomes 1, false becomes 0

    std::cout << value << '\n'; // 1

    int zero = 0;
    bool flag = zero; // 0 becomes false, anything else becomes true

    std::cout << flag << '\n'; // 0

    return 0;
}
```

#### 3. Converting `string` to number (and vice versa)

```cpp
#include <iostream>
#include <string>

int main() {
    std::string ageText = "25";
    int age = std::stoi(ageText); // string -> int

    int score = 99;
    std::string scoreText = std::to_string(score); // int -> string

    std::cout << "Age + 5: " << age + 5 << '\n';
    std::cout << "Score as text: " << scoreText << '\n';

    return 0;
}
```

#### 4. Average of two integers, done correctly

```cpp
#include <iostream>

int main() {
    int a = 5;
    int b = 4;

    // WRONG: (a + b) / 2 gives integer division -> 4 (should be 4.5)
    double average = static_cast<double>(a + b) / 2;

    std::cout << "Average: " << average << '\n'; // 4.5

    return 0;
}
```

#### 5. Losing precision on purpose (narrowing conversion)

```cpp
#include <iostream>

int main() {
    double pi = 3.14159;
    int wholePart = static_cast<int>(pi); // explicitly truncate on purpose

    std::cout << wholePart << '\n'; // 3

    return 0;
}
```

***

### Quick Recap

* **Implicit conversion**: compiler does it automatically (can silently lose data — watch out!).
* **Explicit conversion (casting)**: you do it on purpose, using `static_cast<Type>(value)`.
* Prefer `static_cast` over old C-style `(type)value` casts in modern C++.
* `std::stoi` / `std::to_string` convert between `std::string` and numbers.
* Converting `double` → `int` truncates, it does not round.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/07.-type-conversion.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
