473,320 Members | 1,926 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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 5012
On 8 Mar, 08:29, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.comwrote:
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.comwrote:
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 "comparision 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.comwrote in message
news:11*********************@n33g2000cwc.googlegro ups.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.comwrote 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
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)...
23
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
3
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
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...
6
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...
13
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...
20
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...
10
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
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
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.