Good afternoon, how to make the compiler delete and forget the variable so that it can be initialized again? It is necessary to make the variable not change its name, but change its data type.

include <stdio.h> int main(void) { float a = 10.10; float temp = a; free(a); // просто segmentation fault int a = (int)temp; printf("%d\n", a); // Должно быть 10 } 
  • 2
    No A variable created on the stack exists as long as the program is executed within the scope of this variable (inside curly braces). - maestro
  • 2
    There is an opinion that when such a need arises - it is necessary to revise either the algorithm, or the whole architecture, or even its own life principles :) Even if we are talking about pointers for which void * can roll. - PinkTux
  • @PinkTux There was nothing to do, I wanted to fasten "dynamic typing" to C))) - Teofelts
  • Is she needed there? Yuzayu Since the year since 1994, it seems, there has never been such a need. - PinkTux
  • one
    To find out, it is enough to open any book of the level "C for the smallest". Even an article on the wiki begins with the words "C (C)" - compiled statically typed programming language ... " - PinkTux

2 answers 2

To solve this problem, you can use the fact that in the C language each block (part of the code in curly brackets) forms its own scope:

 #include <stdio.h> int main() { float temp; { float a = 10.1; temp = a; } int a = (int)temp; printf("%d\n", a); } 
  • Thank you, clever way! - Teofelts
  • one
    @Majestio According to the C standard, the return in the main function is allowed. In this case, the compiler itself will implicitly add return 0 . - user194374
  • Hmm ...) Can you credit this? - Majestio
  • @Majestio Can. True, in English. stackoverflow.com/questions/4138649/why-is-return-0-optional - user194374
  • It is the most! Thank. Although, I am not happy - the less “defaults”, the simpler. Otherwise, an IT lawyer will soon be in demand :)). - Majestio

The most convenient way is to use a void * pointer.

 #include<conio.h> #include<stdio.h> #include<stdlib.h> int main(void) { void *a = NULL; a = (void*)malloc(sizeof(int)); (*(int*)a) = 10; printf("%d\n", (*(int*)a)); a = (void*)realloc(a, sizeof(float)); (*(float*)a) = 0.1; printf("%f\n", (*(float*)a)); a = (void*)realloc(a, sizeof(char)); (*(char*)a) = 'A'; printf("%c\n", (*(char*)a)); }