Thread: Casting

  1. #1
    Registered User
    Join Date
    Apr 2008


    Can someone please explain to me how casting works? I lookes online and found very little about it converting other data types to the one I specify. I placed 2 lines of code below. Can someone note what is happening and give me one other example with int? Thanks.

    113     jnl_in.class = (char)class;
    114     jnl_in.mode = (char)mode;

  2. #2
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    On me hyperplane
    It converts a 32 bit integer to an 8 bit char. Since the new container is smaller the data in the top three bytes will be lost. The signed (top) bit in the new char can also cause it to behave differently, for example if it was originally on then the new number will be negative.

  3. #3
    Join Date
    Oct 2007
    Inside my computer
    An explicit cast as it's called simply transforms data from one type to another at the lowest possible level. What it means is that is you try to convert an integer to a char (say 1), you won't get the character '1', but instead some weird character that represents the number 1. It also truncates the value in that the 3 extra bytes worth of data is tossed away since they cannot be represented by a type that is 1 byte (vs 4 bytes).
    When it comes to floating point, however, the compiler is nice enough to perform a read conversion. Converting a float to int will drop the decimals and store the integer part in the integer, for example, even though the data is stored differently in memory.

    There is also a way to change type of data without touching the data itself in memory (the layout of the information will be untouched) by using pointers, but maybe that's a little overcourse.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Casting
    By morvick in forum C++ Programming
    Replies: 2
    Last Post: 06-17-2007, 11:06 PM
  2. Casting Question (I think)
    By fayte in forum C Programming
    Replies: 6
    Last Post: 03-08-2006, 05:31 PM
  3. casting the system exstracted date into seperate ints
    By bazzano in forum C Programming
    Replies: 1
    Last Post: 08-30-2005, 12:17 AM
  4. Type casting
    By Lionmane in forum C Programming
    Replies: 28
    Last Post: 08-20-2005, 02:16 PM
  5. question about casting pointers/other types also??
    By newbie02 in forum C++ Programming
    Replies: 3
    Last Post: 08-07-2003, 05:01 AM