473,545 Members | 1,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing char * with string literal

Suppose we have

char *a = "test message" ;

Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters. So shouldn't the compiler
generate an error/warning for this comparison ?

Mar 8 '07 #1
9 5024
On 8 Mar, 08:29, "subramanian10. ..@yahoo.com, India"
<subramanian10. ..@yahoo.comwro te:
Suppose we have

char *a = "test message" ;

Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters. So shouldn't the compiler
generate an error/warning for this comparison ?
Why? It is pretty much equivalent to

if (address1 == address2)...

which is fairly obviously OK.

Mar 8 '07 #2
On Mar 8, 1:29 pm, "subramanian10. ..@yahoo.com, India"
<subramanian10. ..@yahoo.comwro te:
Suppose we have

char *a = "test message" ;

Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters. So shouldn't the compiler
generate an error/warning for this comparison ?
why ?
strings is an array of characters (terminating with \0 ),
arrays are having base address,string' s base address points to its
first char

you are comparing char * to char * (assume we are not talking about
const)
--Raxit

Mar 8 '07 #3
su************* *@yahoo.com, India wrote:
Suppose we have

char *a = "test message" ;

Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters. So shouldn't the compiler
generate an error/warning for this comparison ?
It's not required to generate a disgnostic. A good warning
for this wouldn't look like the one you're thinking of.

In the expression `a == "string"`, the literal is evaulated
in what I shall call "value" context, as opposed to "target of
assignment" context [1] or "operand of sizeof" context.
Remember that a string literal denotes an array, and that an
array in value context decays into a pointer to its first
element.

So we're comparing `a`, which is a pointer-to-char, to the
address of the `s` in `"string"`, which is pointer-to-char.
No problem, no diagnostic. Happy times!

But [2] ... this is a pretty useless comparision, and not just
because we know that `a` points to a different string; it's
worse than that, Jim.

The only way for the comparision to be true is if `a` points
to that very same `s`. Can it? At first glance no, because
there's no other variable referring to that `s`, and no
other path to get to that literal. So perhaps the compiler
should warn "comparisio n can never succeed"? Again no: suppose
we had

char *a = strchr( "long string", 's' );

so that it points to the `s` in "long string". The compiler
is /permitted/ to have the literal "string" share store with
the tail of "long string".

So the warning might be something like

"that comparision doesn't have a stable result, because
it depends whether whatever `a` points to is part of
some string literal somewhere in this program that ends
with `string`. I suggest you don't do that. Maybe you
should be using `strcmp`?"

And you have to rush out and buy a bigger monitor.

[1] Which I'd call "lvalue" context except I'd risk confusion
and a flame war.

[2] You knew I was going to say that.

--
Chris "electric hedgehog" Dollin
The shortcuts are all full of people using them.

Mar 8 '07 #4
su************* *@yahoo.com, India said:
Suppose we have

char *a = "test message" ;
Better: const char *a = "test message";
>
Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters.
Yes, it is. But it is being used in a value context, and so the address
of its first element is used instead. That address is compared to the
address stored in a. If those addresses are the same, then == will
yield 1 as its result. If the addresses are different (regardless of
the similarity or otherwise of the objects pointed to), then == will
yield 0 as its result.
So shouldn't the compiler
generate an error/warning for this comparison ?
No.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Mar 8 '07 #5
su************* *@yahoo.com, India wrote:
Suppose we have

char *a = "test message" ;

Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters. So shouldn't the compiler
generate an error/warning for this comparison ?
No, because the comparison is perfectly legal. One
can even imagine a scenario where it would "work," such as:

#define YES "Da"
#define NO "Nyet"
const char *decision = NO;
if (this && that && moonPhase() == MOON_FULL)
decision = YES;
doSomething();
if (decision == YES) /* here it is ... */
doMore();

Personally, I would not use strings this way; it's really
using the pointers and not the strings themselves. But
it *is* a legal usage, and the compiler must not reject
the program because of it.

--
Eric Sosman
es*****@acm-dot-org.invalid
Mar 8 '07 #6
Eric Sosman wrote:
No, because the comparison is perfectly legal. One
can even imagine a scenario where it would "work," such as:

#define YES "Da"
#define NO "Nyet"
const char *decision = NO;
if (this && that && moonPhase() == MOON_FULL)
decision = YES;
doSomething();
if (decision == YES) /* here it is ... */
doMore();
A compiler that allocated fresh store for each new string
literal (that's allowed, right?) would be such that
`decision == YES` would never be true.

--
Chris "electric hedgehog" Dollin
Scoring, bah. If I want scoring I'll go play /Age of Steam/.

Mar 8 '07 #7
Chris Dollin wrote On 03/08/07 08:43,:
Eric Sosman wrote:

> No, because the comparison is perfectly legal. One
can even imagine a scenario where it would "work," such as:

#define YES "Da"
#define NO "Nyet"
const char *decision = NO;
if (this && that && moonPhase() == MOON_FULL)
decision = YES;
doSomething();
if (decision == YES) /* here it is ... */
doMore();


A compiler that allocated fresh store for each new string
literal (that's allowed, right?) would be such that
`decision == YES` would never be true.
<fx: self-administered dope slap Yes, of course. It's
been so long since I used a compiler that *didn't* combine
identical literals (and sometimes "suffix literals," too)
that I clean forgot about it.

The code snippet remains legal, but is even stupider
than I thought when I wrote it. (It begins to challenge
my own personal stupidity level ...)

--
Er*********@sun .com
Mar 8 '07 #8

<su************ **@yahoo.comwro te in message
news:11******** *************@n 33g2000cwc.goog legroups.com...
Suppose we have

char *a = "test message" ;

Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters.
Here, evaluation of the expression "string" evaluates
to the address of the character 's'; this value has type
'char *'.

The type of 'a' is also type 'char *'.
So shouldn't the compiler
generate an error/warning for this comparison ?
No. You're comparing two objects of the same type.

-Mike
Mar 8 '07 #9
<su************ **@yahoo.comwro te in message
Suppose we have

char *a = "test message" ;

Consider the comparison

if (a == "string")
.....

Here "string" is an array of characters. So shouldn't the compiler
generate an error/warning for this comparison ?
The language doesn't always do what a programmer familiar with other
languages would expect.
Here the comparison is so unlikely to be a genuine piece of useful code that
a warning is justified, however the compiler writer needs to remember and
put in a special patch just for this situation. Justifiable for a big
compiler, but not for a cheapo one.

There is a similar issue with if( x = 1)
The problem is that constructs like

while( ch = *ptr++ )

are idiomatic and arguably a good thing because they reduce the line count.

Mar 8 '07 #10

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

Similar topics

3
3450
by: Zach | last post by:
What happens when you compare a char against an integer literal? For example, #include <iostream> using namespace std; int main(int argc, char* argv) { signed char c1 = 150; if (c1 < 150) cout << "Less than 150.\n"; else
23
6560
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
3
2871
by: Vishal Ladha | last post by:
Hi ! I have been experimenting with char * for a while now. I have two pieces of code : Code1 : ===== char *ptr = "hello";
13
2583
by: mike79 | last post by:
Hello all, I am a newbie to C, so please bear with me :) I need to create an array in a function (a local variable) with size of 1MB. Since local variables get stored on the stack, at run-time, I get an error. I tried using mallac() function. This function only works when I am allocating memory to a char* and not a char.
6
4740
by: Sona | last post by:
Hi, What's the advantage/disadvantage of using a "const char*" over a "char*" ? I read some place that char* are string literals that on some machines are stored in a read only memory and cannot be modified... does that apply on const char*? thanks Sona
13
6111
by: Nicholas | last post by:
How can I compare char* with integers and characters contained in the str, where integers can be one digit or more? void Access(char *str) { char *pt = str; while (pt != '0') { if (isalpha(*pt)) printf("A character is found\n");
20
7065
by: Petter Reinholdtsen | last post by:
Is the code fragment 'char a = ("a");' valid ANSI C? The problematic part is '("a")'. I am sure 'char a = "a";' is valid ANSI C, but I am more unsure if it is allowed to place () around the string literal.
10
11274
by: william | last post by:
#include <stdio.h> int main() { char *str=NULL; char x="today is good!"; printf("%s", str); str=strtok(x," "); if (str=="today") //<==here is line that confuses me printf("they equals!\n");
13
2707
by: Andreas Eibach | last post by:
Hi, let's say I have this: #include <string.h> #define BLAH "foo" Later on, I do this:
0
7478
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...
0
7410
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...
0
7668
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. ...
1
7437
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7773
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...
1
5343
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...
0
4960
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...
1
1025
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
722
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...

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.