don't click here

Another C Question

Discussion in 'Technical Discussion' started by saxman, May 16, 2009.

  1. saxman

    saxman

    Oldbie Tech Member
    Is it possible to cast a variable where the cast can be a variable amount? Like say I have variable I, and it's an integer. Maybe I want to cast it as a short, or maybe a char, but it depends on the situation. Instead of creating a condition every time I want the program to decide how to cast it, can I put the size I want to cast my I variable as into another variable and simply cast I with the other variable?

    If I didn't explain that clearly enough, let me know. Basically, I'm just trying to save myself from having to write a whole pile of unnecesary code. If I can pass the casting size to a variable and cast somehow using that variable, that would make things really easy.
     
  2. GerbilSoft

    GerbilSoft

    RickRotate'd. Administrator
    2,972
    86
    28
    USA
    rom-properties
    In C, you can use a macro for this sort of thing.

    Code (Text):
    1. #define DO_IT_WITH_SIZE(size, var1, var2) \
    2. do {\
    3.     var1 = ((size)var2);\
    4.     /* other code here */ \
    5. } while (0)
    6.  
    7. int blah()
    8. {
    9.     char a, b;
    10.     int c, d;
    11.     DO_IT_WITH_SIZE(char, a, b);
    12.     DO_IT_WITH_SIZE(int, c, d);
    13. }
    In C++, templates could be used instead:

    Code (Text):
    1. template<typename my_type>
    2. static inline my_type doItWithSize(my_type var1)
    3. {
    4. &nbsp;&nbsp;&nbsp;&nbsp;my_type tmp = var1;
    5. &nbsp;&nbsp;&nbsp;&nbsp;/* other code here */
    6. &nbsp;&nbsp;&nbsp;&nbsp;return tmp;
    7. }
    8.  
    9. int blah()
    10. {
    11. &nbsp;&nbsp;&nbsp;&nbsp;char a, b;
    12. &nbsp;&nbsp;&nbsp;&nbsp;int c, d;
    13. &nbsp;&nbsp;&nbsp;&nbsp;a = doItWithSize(b);
    14. &nbsp;&nbsp;&nbsp;&nbsp;c = doItWithSize(d);
    15. }
     
  3. saxman

    saxman

    Oldbie Tech Member
    Thanks for you help once again Gerbil, I appreciate it!