473,806 Members | 2,371 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

char confusion

I'm trying to find out the ranges of different data types through
direct computation.... ....this is what I did.......

Code:

#include <stdio.h>
main()
{
char ch;
signed short sh;
signed int in;
signed long lo;
unsigned short ush;
unsigned int uin;
unsigned long ulo;
ch = sh = in = lo = ush = uin = ulo = 0;

printf("Ranges through computation:\n\ n");

/* while (ch < (ch+1))
ch++;
printf("The range of a char is from %d to %d\n", ch+1, ch);
*/
while (sh < (sh+1))
sh++;
printf("The range of a short is from %d to %d\n", sh+1, sh);

while (in < (in+1))
in++;
printf("The range of an int is from %d to %d\n", in+1, in);

while (lo < (lo+1))
++lo;
printf("The range of a long is from %ld to %ld\n", lo+1, lo);

while (ush < (ush+1))
++ush;
printf("The range of an unsigned short is from %u to %u\n", ush+1,
ush);

while (uin < (uin+1))
++uin;
printf("The range of an unsigned int is from %u to %u\n", uin+1, uin);

while (ulo < (ulo+1))
++ulo;
printf("The range of an unsigned long is from %lu to %lu\n", ulo+1,
ulo);

return 0;
}

The ranges of all data types in the program print correctly, except for
the char type (the corresponding code is commented out) in which the
loop continues for ever ........why is it so?

Thanks.

Jun 21 '06 #1
8 2231

poodles wrote:
I'm trying to find out the ranges of different data types through
direct computation.... ....this is what I did.......

Code:

#include <stdio.h>
main()
{
char ch;
signed short sh;
signed int in;
signed long lo;
unsigned short ush;
unsigned int uin;
unsigned long ulo;
ch = sh = in = lo = ush = uin = ulo = 0;

printf("Ranges through computation:\n\ n");

/* while (ch < (ch+1))
ch++;
printf("The range of a char is from %d to %d\n", ch+1, ch);
*/
<snip>
return 0;
}

The ranges of all data types in the program print correctly, except for
the char type (the corresponding code is commented out) in which the
loop continues for ever ........why is it so?


Most likely because your `char` is of `unsigned` variety, so `ch+1`
wraps around to 0, instead of the smallest negative value.

Anyway, there's <limits.h> which can tell you all of the above without
breaking a sweat.

Jun 21 '06 #2
poodles wrote:
I'm trying to find out the ranges of different data types through
direct computation.... ....this is what I did.......

[..skip some code...]

/* while (ch < (ch+1))
ch++;
printf("The range of a char is from %d to %d\n", ch+1, ch);
*/
while (sh < (sh+1))
sh++;
printf("The range of a short is from %d to %d\n", sh+1, sh);

[... skip some code ...]
The ranges of all data types in the program print correctly, except for
the char type (the corresponding code is commented out) in which the
loop continues for ever ........why is it so?

Thanks.


On my computer, a sun solaris workstation, compiled with gcc 3.1, it
does endless-loops for all types except long and int types.
The problem you face has nothing to do with char, but how (xx+1) is
treated by your compiler. If xx is a char variable (8bit), but int
on your computer is 16 bit wide then (c+1) has the width of an int.
The same applies for short types on 32 bit machines.

I recommend changing the prog into something like this and it may
function:

while (ch < (char)(ch+1))
ch++;

while (sh < (signed short)(sh+1))
sh++;

or like this (without type casts)

char c1, c2;
for ( c1=0, c2=1; c1 < c2; c1 = c2++ );

Dont forget type casting your (xx+1) in all printf calls.

Best regards,
Bart
Jun 21 '06 #3

Vladimir Oka wrote:
poodles wrote:
I'm trying to find out the ranges of different data types through
direct computation.... ....this is what I did.......

Code:

#include <stdio.h>
main()
{
char ch;
signed short sh;
signed int in;
signed long lo;
unsigned short ush;
unsigned int uin;
unsigned long ulo;
ch = sh = in = lo = ush = uin = ulo = 0;

printf("Ranges through computation:\n\ n");

/* while (ch < (ch+1))
ch++;
printf("The range of a char is from %d to %d\n", ch+1, ch);
*/
<snip>
return 0;
}

The ranges of all data types in the program print correctly, except for
the char type (the corresponding code is commented out) in which the
loop continues for ever ........why is it so?


Most likely because your `char` is of `unsigned` variety, so `ch+1`
wraps around to 0, instead of the smallest negative value.


Strike the above monstrosity! I left the brain on the train...
(See other replies in the thread instead.)
Anyway, there's <limits.h> which can tell you all of the above without
breaking a sweat.


This is still good advice. Relying on overflow behaviour to determine
the ranges of integers is a bad idea in any case.

Jun 21 '06 #4
poodles wrote:

I'm trying to find out the ranges of different data types through
direct computation.... ....this is what I did.......

Code:

#include <stdio.h>
main()
{
char ch; [...] /* while (ch < (ch+1))
ch++;
printf("The range of a char is from %d to %d\n", ch+1, ch);
*/ [...] The ranges of all data types in the program print correctly, except for
the char type (the corresponding code is commented out) in which the
loop continues for ever ........why is it so?


Someone will jump in to correct me if I'm wrong, but I believe it has
to do with type promotions. When you do "ch+1", the result is going
to be protmoted to int (or unsigned int).

So, if you have 8-bit signed chars, then when ch==127, the compare
will be (127 < 128), which is true. But, ch++ results in ch holding
the value -128.

And, if you have 8-bit unsigned chars, then a similar situation
occurs when ch==255. In that case, (255 < 256) is true, but ch++
gives you ch==0.

(Well, actually, I believe that both of the above situations cause
ch++ to be undefined. However, your implementation probably
behaves as I've described.)

Try:

while ( ch < (char)(ch+1) )
ch++;
Now, can someone explain why the same code is working for "short"?

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Jun 21 '06 #5
Kenneth Brody wrote:
poodles wrote:

I'm trying to find out the ranges of different data types through
direct computation.... ....this is what I did.......

Code:

#include <stdio.h>
main()
{
char ch; [...]
/* while (ch < (ch+1))
ch++;
printf("The range of a char is from %d to %d\n", ch+1, ch);
*/

[...]
The ranges of all data types in the program print correctly, except for
the char type (the corresponding code is commented out) in which the
loop continues for ever ........why is it so?


Someone will jump in to correct me if I'm wrong, but I believe it has
to do with type promotions. When you do "ch+1", the result is going
to be protmoted to int (or unsigned int).

So, if you have 8-bit signed chars, then when ch==127, the compare
will be (127 < 128), which is true. But, ch++ results in ch holding
the value -128.

And, if you have 8-bit unsigned chars, then a similar situation
occurs when ch==255. In that case, (255 < 256) is true, but ch++
gives you ch==0.

(Well, actually, I believe that both of the above situations cause
ch++ to be undefined. However, your implementation probably
behaves as I've described.)


Assuming char promotes to int, ch++ means "ch = (char) ((int) ch + 1)".
Behaviour after overflow in signed arithmetic (which can happen only if
CHAR_MAX == INT_MAX, so never if CHAR_MAX == 127) is undefined, but
overflow in signed conversions results either in an
implementation-defined value, or an implementation-defined signal
(which can but doesn't have to have UB).

And for unsigned char, behaviour is defined (this time assuming
UCHAR_MAX != INT_MAX) as you expected the implementation would behave.
Try:

while ( ch < (char)(ch+1) )
ch++;
Now, can someone explain why the same code is working for "short"?


Possibly because on that particular system, SHRT_MAX == INT_MAX.

Jun 21 '06 #6
Thanks a lot Bart Rider, Kenneth Brody and Harald van Dijk; that's the
solution I was looking for. Perhaps it is a "bad idea", but I was
trying to solve Exercise 2-1, page 36 in K&R's book.:

"Write a program to determine the ranges of char , short , int , and
long variables, both signed and unsigned , by printing appropriate
values from standard headers and by direct computation. Harder if you
compute them: determine the ranges of the various floating-point
types."

Please let me know a better idea to solve the above problem........ ..
Also I can't think of a way to *compute* the ranges of floating point
types....I'd be grateful if someone can help.....

Thanks

Jun 21 '06 #7
poodles wrote:

Thanks a lot Bart Rider, Kenneth Brody and Harald van Dijk; that's the
solution I was looking for. Perhaps it is a "bad idea", but I was
trying to solve Exercise 2-1, page 36 in K&R's book.:

"Write a program to determine the ranges of char , short , int , and
long variables, both signed and unsigned , by printing appropriate
values from standard headers and by direct computation. Harder if you
compute them: determine the ranges of the various floating-point
types."

Please let me know a better idea to solve the above problem........ ..
Well, if you're not strictly concerned about portability, the odds
are that something like this will work on your platform:

unsigned whatever u = (unsigned whatever)-1L;
signed whatever s = (signed whatever)(u >> 1);

where "whatever" is char/short/int/long.

Again, note my qualifier "the odds are", since the above is bound to
cause problems on some platforms.

And note that this only gives the high end of the range. I suppose
that, once again, "the odds are" that incrementing each of the
variables will wrap to the low end.

A quick test on my platform shows this technique "works" on this
particular hardware/software combination.

char: -128/127 0/255
short: -32768/32767 0/65535
int: -2147483648/2147483647 0/4294967295
long: -2147483648/2147483647 0/4294967295
Also I can't think of a way to *compute* the ranges of floating point
types....I'd be grateful if someone can help.....


I don't think that's computable. (Note that the K&R assignment
doesn't ask about those.)

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Jun 21 '06 #8
Thanks for the reply, Kenneth Brody

Jun 23 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2757
by: LongBow | last post by:
Hello all, From doing a google serach in the newsgroups I found out that a string can't be returned from a function, but using a char* I should be able to do it. I have spent most of the day trying to get this to work, but been unable to solve my mistake. What the function should return is a file name used for creating logs files. It will look something like JN122345.log
9
4180
by: dam_fool_2003 | last post by:
For int data type the default range starts from signed to unsigned. If we don't want negative value we can force an unsigned value. The same goes for long also. But I don't understand why we have signed char which is -256. Does it means that we can assign the same ASCII value to both signed and unsigned. That means the ASCII value can be represented with a type of signed char and also unsigned char? For example int main(void) {
5
3991
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a variable **var make it an array of pointers? I realize that 'char **var' is a pointer to a pointer of type char (I hope). And I realize that with var, var is actually a memory address (or at
12
5537
by: arkobose | last post by:
my earlier post titled: "How to input strings of any lengths into arrays of type: char *array ?" seems to have created a confusion. therefore i paraphrase my problem below. consider the following program: #include<stdio.h> #define SIZE 1 int main()
2
7660
by: Michael | last post by:
Hi, How to understand the difference between the following three. My understanding is the number in bracket minus one is the max number of chars to store in the char array , right? Thanks in advance.
14
27192
by: metamorphiq | last post by:
Hello, I'm a Java programmer, so I'm probably asking a very simple question here, but I have trouble solving it :) I'd like to know how you concatenate multiple (4, in my case) char* in C++, and have the result as a char*. I first tried using strcat, but you need a const char* as the second parameter to work, but I don't know all the issues regarding const chars, so maybe I overlooked something.
3
3497
by: ZMan | last post by:
The following code won't compile with gcc version 3.4.2 (mingw-special). How come? Error: cannot convert `char (*)' to `char**' /**********************************************************/ #include <cstdio> #define MAX_WORD_LEN 80 #define MAX_SIZE 1000
9
2273
by: happyvalley | last post by:
I just wonder how to pass arguments to this function with a char** void oldmain(int argv, char**argc) { ........ } void main(void) { int argv;
19
2141
by: arnuld | last post by:
i am trying to understand arrays and char. Stroustrup says, this a string literal: "this is a string literal" he says it is of type /const char/. he also says, because of keeping compatibilities with previous definitions of C & C++, it is also a CHAR POINTER a.k.a /char*/. however it is an error, which can not be caught at untill runtime, to modify a string literal using such pointer:
9
10532
by: Peithon | last post by:
Hi, This is a very simple question but I couldn't find it in your FAQ. I'm using VC++ and compiling a C program, using the /TC flag. I've got a function for comparing two strings int strspcmp(const char * s1, const char * s2) {
0
9719
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10618
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10110
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9187
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4329
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.