M
M
Mishka_Sev2020-07-16 02:30:30
C++ / C#
Mishka_Sev, 2020-07-16 02:30:30

How to convert type in C?

The cast is done by writing the type in parentheses next to the identifier in the expression?

#include <stdio.h>

int main() {

    int i = 1;
    i = (float)i;  // попытка из int сделать float

    printf("%f", i); // выводим на экран float


return 0;
}


Why doesn't it work, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
wisgest, 2020-07-17
@Mishka_Sev

i = (float)i;
— Since the variable on the left iis of type int, the value of the expression on the right (float)iwill be converted back to when assigned int.
printf("%f", i);
- The memory area starting from the address at which the printfvalue of the intvariable type is placed on the stack when called i(and, accordingly, occupying sizeof (int)bytes) is interpreted as storing the value of the type float( sizeof (float)bytes in size and additionally capturing extraneous garbage from the stack). That is, this is not even an arithmetic (even with rounding) conversion.
Should work:
int main() {

    int i = 1;

    printf("%f", (float)i); // выводим на экран float


return 0;
}

R
Rsa97, 2020-07-16
@Rsa97

Because in C the type of a variable is declared once and does not change. Only the value of a variable or expression can be cast to another type.

C
CityCat4, 2020-07-16
@CityCat4

That's it :)
Type casting is not an operation on a value , but an operation on an address . It doesn't change the value, it changes the compiler's attitude towards the pointer to the given object.

int i = 10;
int *p = &i;
char *c = (char *) p;

*c = '\xFF';

Question - where will 0xFF be written? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question