473,769 Members | 5,374 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array Lookup [Was: Why is "Hello World" const char* ?]

Hello,

Thanks for all your response on my question about signed/unsigned chars.

The problem is this: I want to use the char array for a ArrayLookup, so
I need to convert char to unsigned int.

But this doesn't work!

If I try this:

#include <stdio.h>
int main() {
char c = -1; // 129 unsigned and -1 signed right?
// convert it to a value between 0 - 255 for array Lookup
unsigned int arrayIndex = (unsigned int) c;
if (arrayIndex < 0)
printf("ArrayIn dex still negative after conversion to unsigned int
%d\n",arrayInde x);
else
printf("Unsigne d representation is OK for ArrayIndex=%d\n ",arrayInde x);
}

The output is: "ArrayIndex still negative after conversion to unsigned
int -1"

How is this possible?

I would expect a output 129.

Thanks!

Hans
Jul 23 '05 #1
13 2504
Hans wrote:
Hello,

Thanks for all your response on my question about signed/unsigned chars.

The problem is this: I want to use the char array for a ArrayLookup, so
I need to convert char to unsigned int.

But this doesn't work!

If I try this:

#include <stdio.h>
int main() {
char c = -1; // 129 unsigned and -1 signed right?
Wrong.

// convert it to a value between 0 - 255 for array Lookup
unsigned int arrayIndex = (unsigned int) c;

The casting is not needed.

Also this is equivalent to

unsigned int arrayIndex = numeric_limits< unsigned int>::max();
or UINT_MAX of <climits>.


if (arrayIndex < 0)
printf("ArrayIn dex still negative after conversion to unsigned int
%d\n",arrayInde x);
else
printf("Unsigne d representation is OK for ArrayIndex=%d\n ",arrayInde x);
}

The output is: "ArrayIndex still negative after conversion to unsigned
int -1"

How is this possible?

%d is for int, %u is for unsigned int.
I just noticed you are cross posting to clc, usually a bad thing to do
since C and C++ are different languages.
Anyway your program fixed and being valid C99 and C++03:
#include <stdio.h>
#include <limits.h>

int main()
{
char c = -1;

unsigned int arrayIndex = c;

if (arrayIndex < 0)
printf("ArrayIn dex still negative after conversion to unsigned
int %u\n",arrayInde x);

else
printf("Unsigne d representation is OK for
ArrayIndex=%u\n \n",arrayIndex) ;
printf("UINT_MA X is %u\n", UINT_MAX);
}


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #2
Hans wrote:
The output is: "ArrayIndex still negative after conversion to unsigned
int -1"

How is this possible?

Still, the original erroneous code did not print the above.


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #3
Hans wrote:
Hello,

Thanks for all your response on my question about signed/unsigned chars.

The problem is this: I want to use the char array for a ArrayLookup, so
I need to convert char to unsigned int.

But this doesn't work!

If I try this:

#include <stdio.h>
int main() {
char c = -1; // 129 unsigned and -1 signed right?
Wrong. c is either -1 or UCHAR_MAX (for CHAR_BIT==8: 255)
// convert it to a value between 0 - 255 for array Lookup
Wrong. You either get UCHAR_MAX or UINT_MAX from the following
unsigned int arrayIndex = (unsigned int) c;
Probably, you want to have ... = (unsigned char) c;
Otherwise, the cast is unnecessary.
if (arrayIndex < 0)
printf("ArrayIn dex still negative after conversion to unsigned int
%d\n",arrayInde x); %u; you are lying about the type, so printf() will get it wrong. else
printf("Unsigne d representation is OK for ArrayIndex=%d\n ",arrayInde x); Dito. }

The output is: "ArrayIndex still negative after conversion to unsigned
int -1"
You are lying. The output of the above probably is
"Unsigned representation is OK for ArrayIndex=-1\n"
Anything else is not possible.
How is this possible?
It ain't.
I would expect a output 129.
I would expect for CHAR_BIT==8 either 255 or -1 and for the fixed
printf() format string either 255 or UINT_MAX which is probably either
2**16-1 or 2**32-1 (65,XXX or 4,XXX,XXX,XXX).

See also the replies of Ioannis Vranos.

Please get decided whether to post in clc or clc++.
F'up2 clc
Thanks!


You're welcome.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jul 23 '05 #4
Hans <Ha**@replyingr ouptoavoidspam. com> writes:
[...]
If I try this:

#include <stdio.h>
int main() {
char c = -1; // 129 unsigned and -1 signed right?
// convert it to a value between 0 - 255 for array Lookup
unsigned int arrayIndex = (unsigned int) c;
if (arrayIndex < 0)
printf("ArrayIn dex still negative after conversion to unsigned int
%d\n",arrayInde x);
else
printf("Unsigne d representation is OK for ArrayIndex=%d\n ",arrayInde x);
}

The output is: "ArrayIndex still negative after conversion to unsigned
int -1"


Why did you cross-post to comp.lang.c and comp.lang.c++? There's
nothing specific to C++ in your program (except possibly the comments
and the missing return statement). Remember, C and C++ are two
different languages.

It's best to use /*...*/ comments when posting to comp.lang.c. Not
all C compilers support // comments, and they're more vulnerable to
being split across lines by news software.

You should also keep your source lines relatively short. The string
literal in your first printf() was split.

Assuming CHAR_BIT==8 (and UCHAR_MAX==255) , the unsigned equivalent of
-1 is 255, not 129.

The cast on the initialization of ArrayIndex is superfluous; the value
is going to be converted to unsigned int anyway.

You should have a "return 0;" at the end of your main program. It's
not strictly required in C99 or C++, but it is in C90 (if you don't
want to return an undefined exit status).

You're using the wrong printf format for arrayIndex. The variable is
of type unsigned int; you need to use "%u", not "%d".

Having said all that, I can't reproduce the problem you describe. The
value assigned to arrayIndex is going to change depending on whether
"plain" char is signed or unsigned. If it's unsigned, c is set to
UCHAR_MAX (typically 255), and arrayIndex is set to the same value.
If plain char is signed, c is set to -1, and arrayIndex is set to
UINT_MAX (typically 4294967295 on 32-bit systems) -- which is likely
to be printed as "-1" if you use the incorrect "%d" format. (I think
C++ behaves the same way as C.)

If you want to use a char to store a value that has to be
non-negative, use an unsigned char, not a plain char. Plain char may
happen to work on your system, but your code is likely to break on
others (and it's more difficult to determine what the code is going to
do if you leave the signedness up to the compiler).

By using (unsigned) char as an array index, you're limiting the index
values to 255 (potentially more on exotic systems with CHAR_BIT > 8,
but 255 is the portable limit). Not knowing anything about your
application, I can't guess whether that's a potential problem.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 23 '05 #5
Followup-to: header ignored.

Michael Mair <Mi**********@i nvalid.invalid> writes:
Hans wrote:

[...]
The output is: "ArrayIndex still negative after conversion to
unsigned int -1"


You are lying. The output of the above probably is
"Unsigned representation is OK for ArrayIndex=-1\n"
Anything else is not possible.


I don't see how the posted program could print what Hans says it does,
but it's not necessary to accuse him of lying. He might have mis-read
the output, he might have posted code that didn't match what he
actually compiled, or he might even have a buggy compiler.

If he's wrong, say so, but we don't know enough to assume that he's
being deliberately dishonest.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 23 '05 #6

Hans wrote:
Hello,

Thanks for all your response on my question about signed/unsigned chars.
The problem is this: I want to use the char array for a ArrayLookup, so I need to convert char to unsigned int.

But this doesn't work!

If I try this:

#include <stdio.h>
int main() {
char c = -1; // 129 unsigned and -1 signed right?
// convert it to a value between 0 - 255 for array Lookup
unsigned int arrayIndex = (unsigned int) c;
if (arrayIndex < 0)
printf("ArrayIn dex still negative after conversion to unsigned int %d\n",arrayInde x);
else
printf("Unsigne d representation is OK for ArrayIndex=%d\n ",arrayInde x); }

The output is: "ArrayIndex still negative after conversion to unsigned int -1"

How is this possible?

I would expect a output 129.

Thanks!

Hans


- specifier for unsigned int is %u, not %d
- always return 0 before the final brace of main
- your expected output of 129 is unreasonable, you're either going to
get UCHAR_MAX or UINT_MAX.
- the statement after else should always execute, because an unsigned
int is never less than 0
- either you are lying (which I doubt), your compiler is wrong, or the
undefined behaviour your original code falls into affected your results

Jul 23 '05 #7
Keith Thompson wrote:
Followup-to: header ignored.

Michael Mair <Mi**********@i nvalid.invalid> writes:
Hans wrote:


[...]
The output is: "ArrayIndex still negative after conversion to
unsigned int -1"


You are lying. The output of the above probably is
"Unsigned representation is OK for ArrayIndex=-1\n"
Anything else is not possible.

I don't see how the posted program could print what Hans says it does,
but it's not necessary to accuse him of lying. He might have mis-read
the output, he might have posted code that didn't match what he
actually compiled, or he might even have a buggy compiler.

If he's wrong, say so, but we don't know enough to assume that he's
being deliberately dishonest.


You are right, that was not what I intended to say and way too harsh.
I apologize for that.
-Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jul 23 '05 #8
Keith Thompson wrote:
Followup-to: header ignored.

Michael Mair <Mi**********@i nvalid.invalid> writes:
Hans wrote: [...]
The output is: "ArrayIndex still negative after conversion to
unsigned int -1"


You are lying. The output of the above probably is
"Unsigned representation is OK for ArrayIndex=-1\n"
Anything else is not possible.


I don't see how the posted program could print what Hans says it

does, but it's not necessary to accuse him of lying. He might have mis-read the output, he might have posted code that didn't match what he
actually compiled, or he might even have a buggy compiler.

If he's wrong, say so, but we don't know enough to assume that he's
being deliberately dishonest.

I don't think Mike meant the OP was truly lying for the purpose of
confusing c.l.c readers. He probably meant it as if he was suprised,
kind of like if someone says something unbelievable you might respond:
"No way, you're lying."

He did further go on to help the OP, so lighten up Keith. If you're
going to be such a hard a*s about every post on c.l.c. that is even a
little OT, incorrect or improper, then lead by example.

In the thread titled: "Do you like my strlcpy strlcat etc?" you join in
with other posters to mock the use of symabolic constants by the OP.
The OP didn't deserve that and everyone who responded just made fun of
him/her. You took part in a session where people kept making worse
versions of the original preprocessor defines. Not everyone has been
roaming c.l.c and programming in C for ages, so lighten up "a little"
or apply the same strict rules you enforce on yourself.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst> San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst> We must do something. This is something. Therefore, we must do this.


Jul 23 '05 #9
Ioannis Vranos wrote:
The casting is not needed.

Also this is equivalent to

unsigned int arrayIndex = numeric_limits< unsigned int>::max();
or UINT_MAX of <climits>.

Actually this is the case when char is signed.
--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #10

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

Similar topics

31
630
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
15
416
by: Hans | last post by:
Hello, Thanks for all your response on my question about signed/unsigned chars. The problem is this: I want to use the char array for a ArrayLookup, so I need to convert char to unsigned int. But this doesn't work! If I try this:
3
2354
by: lovecreatesbeauty | last post by:
Both `K&R C, 2nd' and `C: A reference manual, 5th' introduce the "hello, world" thing using the name "string-constant". But `ISO/IEC 9899:TC2' does not include this kind of thing in section `A.1.5 Constants'.
10
5356
by: fei.liu | last post by:
Consider the following sample code char * ptr = "hello"; char carray = "hello"; int main(void){ } What does the standard have to say about the storage requirement about ptr and carray? Is it a fair statement that char *ptr will take 4 more bytes (on 32bit platform) in DATA segment? I have found
3
2816
by: amanjsingh | last post by:
I want to know what is the origin of Hello World program and who wrote it, what language it was written in and why was Hello World chosen as a phrase? Thanks a lot AJ
0
9589
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
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10214
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
10048
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
9865
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...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3963
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

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.