Why type conversion gets stuck while promotion in C?

Walkbitterwyrm Lightwarg 20 Reputation points
2023-09-04T06:35:27.3533333+00:00

Why the type conversion gets stuck when doing the type conversion from int to float (promotion) but works when converting float to int (demotion).

#include <stdio.h>

int main()
{
    int i, *ptr_i;
    float f, *ptr_f;

    i = 65;
    f = 65.5;

    *ptr_i = (int) f; // Demotion with explicit type casting

    printf("%d", *ptr_i); // Data loss can occur while printing the value

    *ptr_f = (float) i; // Demotion with explicit type casting

    printf("%f", *ptr_f); // Data loss can occur while printing the value

    return 0;
}

The demotion works only when promotion is not done.

#include <stdio.h>

int main()
{
    int i, *ptr_i;
    float f, *ptr_f;

    i = 65;
    f = 65.5;

    *ptr_f = (float) i; // Demotion with explicit type casting

    printf("%f", *ptr_f); // Data loss can occur while printing the value

    return 0;
}

The above program works because there was no demotion.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
3,778 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,962 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,175 questions
{count} votes

Accepted answer
  1. WayneAKing 4,356 Reputation points
    2023-09-04T08:00:18.4733333+00:00

    You have declared the pointer variables ptr_i and ptr_f but have never assigned an address to either of them. As they are local variables their contents will be indeterminate. They may contain any value, and therefore attempting to dereference them will be meaningless and may try to access invalid or inaccessible memory locations.

    As your earlier code examples in other threads correctly assign usable addresses to these pointer variables before trying to use them, you already know how to do that.

    ptr_i = &i;

    ptr_f = &f;

    • Wayne

0 additional answers

Sort by: Most helpful