Thread: question about casting pointers/other types also??

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    15

    question about casting pointers/other types also??

    Hi,

    I have been trying to figure out casting, and have a quick question I hope someone can help me with:

    What exactly is the purpose of casting, like for int, char...etc...:
    example:
    int x = 5;
    (char) x;

    I am confused about this? what does it mean, and why is it needed??


    Also, I keep seeing code where it mentions casting a pointer:
    example:
    (void *) something;

    Could someone please explain what casting a pointer means and why it is needed??

    Thanks a lot for any explanation! It is appreciated!

  2. #2
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    First, typecasting isn't used that often.

    It is used when a number passed to a function is different from what the function requires. If your function expects an int, and you only have a char, you need to cast the char to an int.

    This shouldn't happen if you wrote the program and the function yourself, but it could happen if you are using a library function.

    A void pointer is a pointer that can point to any type. There's some info from a tutorial at cplusplus.com (Look for "void pointers" near the bottom of the page.)

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    15

    thanks

    Thank you, it makes much more sense now , thanks a lot!

  4. #4
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    >> First, typecasting isn't used that often.

    Perhaps with simple data types, but typecasting is almost always used in almost every C++ program where classes or templates are used.

    It is important to understand how C++ typecasting works.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. invalid types 'int[int]' for array subscript
    By kolistivra in forum C++ Programming
    Replies: 6
    Last Post: 12-11-2010, 12:57 PM
  2. Replies: 6
    Last Post: 08-23-2008, 01:16 PM
  3. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  4. Exam Question - Possible Mistake?
    By Richie T in forum C++ Programming
    Replies: 15
    Last Post: 05-08-2006, 03:44 PM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM