Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
i = (float)i;— Since the variable on the left
i
is of type int
, the value of the expression on the right (float)i
will be converted back to when assigned int
.printf("%f", i);
- The memory area starting from the address at which the printf
value of the int
variable 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. int main() {
int i = 1;
printf("%f", (float)i); // выводим на экран float
return 0;
}
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.
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';
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question