-1

Could please tell why compiler is not allowing this type cast...Error compiler showing is " Invalid static_cast from float * to int * "

#include<iostream>
using namespace std;
int main()
{
   float f=45.678;
   float *a;
   a=&f;
   int *d;
   cout<<static_cast<int *>(a);
}
Scis
  • 2,934
  • 3
  • 23
  • 37
virusai
  • 27
  • 1
  • 7
  • possible duplicate of [C++: can't static\_cast from double\* to int\*](http://stackoverflow.com/questions/2473628/c-cant-static-cast-from-double-to-int) – Scis Mar 01 '15 at 13:04
  • 2
    Why *should* it allow the cast? – Christian Hackl Mar 01 '15 at 13:38
  • Because casting was meant to allow conversion between different data types...@christian hackl – virusai Mar 01 '15 at 13:45
  • need possibly more simpler and deeper explanation @scis – virusai Mar 01 '15 at 13:48
  • @virusai: C++-style casts are explicitly designed to allow only *certain* types of casts. That's one of the great things about them; unlike C-style casts, they prevent accidental casts and silent bugs. What's wrong with the answer linked to by Scis? – Christian Hackl Mar 01 '15 at 13:53
  • Please read this answer which gives a great summary of [what different casts do in C++](http://stackoverflow.com/a/332086/3848) – Motti Mar 01 '15 at 13:53
  • possible duplicate of [When should static\_cast, dynamic\_cast, const\_cast and reinterpret\_cast be used?](http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used) – Motti Mar 01 '15 at 13:54
  • @virusai Casting was meant to allow *sane* conversion between different data types. Converting between`int*` and `float*` will cause problems, therefore not allowed. – L. F. Mar 24 '19 at 02:56

1 Answers1

2

static_cast is a cast that makes a compile-time check if the cast is legal.

Consider following examples of when cast is legal:

  • casting a smaller-size signed/unsigned integer type to bigger size signed/unsigned integer type with
  • upcasting pointer to derived class to pointer to base class.
  • and so on.

Casting float* to int* doesn't make sense from a standpoint of the compiler. If you want to make a such conversion, you should use reinterpret_cast.

JustSomeGuy
  • 3,677
  • 1
  • 23
  • 31