cast cpp

#include <iostream>
using namespace std;

int main() {
    float f = 10.5;
    int i;

    i = static_cast<int>(f);

    cout << "Float f: " << f << endl;
    cout << "Int i after casting: " << i << endl;

    return 0;
}

Explanation:

  • #include <iostream>: Includes the input/output stream library to perform input and output operations.
  • using namespace std;: Allows the usage of elements in the std namespace without prefixing them with std::.
  • int main() { ... }: The main function where the program execution begins.
  • float f = 10.5;: Declares and initializes a float variable f with the value 10.5.
  • int i;: Declares an integer variable i.
  • i = static_cast<int>(f);: Uses static_cast to explicitly convert f from a float to an integer, assigning the result to i.
  • cout << "Float f: " << f << endl;: Outputs the value of variable f.
  • cout << "Int i after casting: " << i << endl;: Outputs the value of variable i after the casting operation.
  • return 0;: Indicates successful program execution and terminates the main function.