Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Cast question (http://www.go4expert.com/forums/cast-question-t4423/)

bughunter2 25May2007 17:34

Cast question
 
For example I have this code:

Code:

            /* increase gravity */
            if((1000/60) /* 60 Hz */ > m_iGravity)
            {
                --m_iGravity;
            }

Now 'm_iGravity' is declared as type 'int'. The compiler warning is: "comparison between signed and unsigned integer expressions".

When I cast 'm_iGravity' as '(unsigned int)' I still get this warning, but if I modify the declaration of 'm_iGravity' to 'unsigned int' I get no warning. I also tried casting the result of the division result, but no luck.

Can anyone give me a hand with this?

DaWei 25May2007 17:49

Re: Cast question
 
You get the warning because the comparison could give you an error. For simplicity, consider that an int or unsigned int were one byte. 0xff would be -1 for the int, but 255 for the unsigned int. Casting won't fix the problem. It'll make the conversion, alright, but if you assign it to an int, that int will be interpretated, later, as an int. The cast converts the value, not the type of variable assigned to. All those could get you into an error situation. When you cast the result of the division, you should cast it to int, to match gravity, not unsigned int.

bughunter2 25May2007 23:24

Re: Cast question
 
Yes I understand it. However, I have already tried to cast the result of the division as 'int' and it didn't work. Could you show me the correct way of casting (maybe I'm doing it totally wrong?).

bughunter2 25May2007 23:25

Re: Cast question
 
I tried the following to cast the division result:

Code:

            /* increase gravity */
            if((int)(1000/60) /* 60 Hz */ > m_iGravity)
            {
                --m_iGravity;
            }


bughunter2 25May2007 23:52

Re: Cast question
 
Oh I'm sorry I was looking at the wrong line (been coding too long of course!).

Actually the warning was about another line so that's why casting the result of the division didn't help anything.

I'm very thankful though for your explanation, it helped me understand errors of the same type that I had for some of my other programs.


All times are GMT +5.5. The time now is 17:00.