HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

C Type Conversion


C Type Conversion: C offers several ways to convert data from one type to another. Understanding these conversions is crucial for writing efficient and accurate code.


When working with integers in C, division (/) performs integer division, which discards the fractional part of the result and only keeps the whole number quotient. This is why dividing 5 by 2 only outputs 2, as 2.5 gets truncated to 2:


Example

#include

int main() {

int x = 5;


int y = 2;

int sum = 5 / 2;


printf("%d", sum);

return 0;

}


Output

2


To get the right result, you need to know how type conversion works.


There are two types of conversion in C:


Implicit Conversion (automatically)

Explicit Conversion (manually)8



Implicit Conversion

Implicit Conversion (automatic): The compiler automatically converts values between compatible types during operations like arithmetic expressions. For example, adding an int and a float implicitly converts both to float before performing the calculation.


Explicit Conversion (manually)

Explicit Conversion (manual): You explicitly cast a value to a different type using the casting operator (type_name) expression. This allows converting incompatible types but requires caution due to potential data loss or undefined behavior.


For example, if you assign an int value to a float type:


Example

#include

int main() {

// Automatic conversion: int to float


float myFloat = 9;


printf("%f", myFloat);

return 0;

}


Output

9.000000