Advertisement

Simple C++ program

Started by August 25, 2000 09:28 PM
2 comments, last by boolean010 24 years, 4 months ago
    

// I''m not really that new to C++, but here''s the problem: an 
// unsigned char can represent values between 0 and 255, right?
// Well, why does the code listed below fail to work.

// Example 1

typedef unsigned char UCHAR;

for ( UCHAR i=0; i<256; i++ ) {
    cout << (int) i;
}
cout << endl;

// Example 1 just goes on forever until I kill the program.

// Ok, so I said to myself, maybe it''s because I''m comparing 
// an unsigned char to 256, and that''s probably where the problem
// lies, so I decided to try Example 2, only to get 
// same results


// Example 2

for ( UCHAR i=0; i<=255; i++ ) {
    cout << (int) i;
}
cout << endl;

// By the way, I''m using MSVC++ 6.0 on a win98 machine

    
** boolean010 **
It keeps wrapping back over to zero before it gets to 256 (remember, the values are from 0 to 255!). That's why it goes on infinitely.

lntakitopi@aol.com - http://www.geocities.com/guanajam

Edited by - SHilbert on August 25, 2000 10:35:12 PM
Advertisement
SHilbert is right

Why not use a simple int instead of UCHAR? It''s probably even faster, because most compilers often convert bytes into int''s, sometimes even where it''s not needed (at asm level)...!

Thanks for the info. I was just fooling around and stuff.
Hoping I might be able to make a discovery of some kind
** boolean010 **

This topic is closed to new replies.

Advertisement