Happy Mittal
Happy Mittal

Reputation: 3747

Explicit type conversion

I have read in a book that specifies this :

//: C03:SimpleCast.cpp
int main() {
int b = 200;
unsigned long a = (unsigned long int)b;
} ///:~

"Casting is powerful, but it can cause headaches because in some situations it forces the compiler to treat data as if it were (for instance) larger than it really is, so it will occupy more space in memory; this can trample over other data. This usually occurs when casting pointers, not when making simple casts like the one shown above."

Now can You please provide an example where casting pointer can trample other data?

Upvotes: 0

Views: 484

Answers (4)

franji1
franji1

Reputation: 3156

Since this was tagged as C++, not C, I also recommend reading up on C++ style casts over C style casts:

static_cast<Derived *>(pBase)->DMethod();
if (dynamic_cast<Derived *>(pBase)) dynamic_cast<Derived *>(pBase)->DMethod();
const_cast<CRect &>(constRect).x = 3;
int *pInt = reinterpret_cast<int *>(charbuff);

I highly recommend Scott Myer's book Effective C++, 55 Specific Ways to Improve Your Programs and Designs, 3rd Edition that explains these very well. Make sure you get the 3rd Edition, although the 2nd Edition may also have covered C++ style casts too.

Basically, if you are using C++ and your compiler was written within the last 10 years, NEVER use C-style casts. Use C++ style casts.

Upvotes: 0

Ken Bloom
Ken Bloom

Reputation: 58770

char unix[5]="unix";
char* first= &(unix[0]);
int * intptr= (int*) first;
*first=64;
printf("%s\n",unix); /* prints @ /*

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490128

int main() { 
    char a[] = "This is a string.";

    *(long *)a = 12345678;  // will typically overwrite first four or eight bytes of a.

    std::cout << a;
    return 0;
}

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

int main(void)
{
    short int a = 5;
    short int b = 7;
    *(long int*)&a = 0;
}

Assuming sizeof(long) > sizeof(short), and assuming the compiler puts a on the stack before b, b will be trashed.

Upvotes: 5

Related Questions