Charlie Gordon wrote On 09/19/07 09:07,:
> "Junmin H." <> a écrit dans le message de news:
> ...
>
>>On Thu, 13 Sep 2007 00:56:59 +0200, Charlie Gordon wrote:
>>
>>
>>>"Junmin H." <> a écrit dans le message de news:
>>>46e7722e$0$24006$.. .
>>>
>>>>Hello, I am trying to print the range of unsigned char and unsigned int.
>>>>The one for char is working good, gives me a correct output,
>>>>however the other one for int doesnt, why?? Thanks
>>>>
>>>>#include <stdio.h>
>>>>
>>>>main(){
>>>> unsigned char c, temp;
>>>> c = temp = 0;
>>>> printf("the range of unsigned char is from %d to ", c);
>>>> while(c >= temp){
>>>> temp = c;
>>>> ++c;
>>>> }
>>>> printf("%d\n", temp);
>>>> return 0;
>>>>}
>>>>
>>>>OUTPUT: the range of unsigned char is from 0 to 255
>>>
>>>A much simpler version, that works in C99 and before :
>>>
>>>replace the while loop with
>>>
>>>temp = c - 1;
>>>
>>>and you are done.
>>>
>>>
>>>>#include <stdio.h>
>>>>
>>>>main(){
>>>> unsigned int c, temp;
>>>> c = temp = 0;
>>>> printf("the range of unsigned int is from %d to ", c);
>>>> while(c >= temp){
>>>> temp = c;
>>>> ++c;
>>>> }
>>>> printf("%d\n", temp);
>>>> return 0;
>>>>}
>>>>
>>>>OUTPUT: the range of unsigned int is from 0 to -1
>>>
>>>temp = c - 1; works here too, and is much more efficient, O(1) obviously
>>>
>>>
>>>it actually works for any unsigned type.
>>
>>I'm sorry. I don't understand your point.
>>
>
>
> No loop is needed, the following code is portable to all platforms.
>
> #include <stdio.h>
> int main(void){
> printf("the range of unsigned char is from 0 to %u\n",
> (unsigned char)-1);
> printf("the range of unsigned short is from 0 to %u\n",
> (unsigned short)-1);
> printf("the range of unsigned int is from 0 to %u\n",
> (unsigned int)-1);
> return 0;
> }
"I ran it on my DeathStation 9000 and demons flew
out of my nose."
Suggested fix:
#include <stdio.h>
int main(void){
printf("the range of unsigned char is from 0 to %u\n",
(unsigned int)(unsigned char)-1);
printf("the range of unsigned short is from 0 to %u\n",
(unsigned int)(unsigned short)-1);
printf("the range of unsigned int is from 0 to %u\n",
(unsigned int)-1);
return 0;
}
References:
7.19.6.1p8: "[...] o,u,x,X The unsigned int argument is
converted [...]"
7.19.6.1p9: "[...] If any argument is not the correct
type for the corresponding conversion specification, the
behavior is undefined."
6.3.1.1p3: "[...] If an int can represent all values of
the original type, the value is converted to an int; [...]"
--