String constant in compare operation

C

C. J. Clegg

Consider this code:

char* s;
char* putSomethingThere( void );

s = putSomethingThere( );

if( s == "abc" )
{
...
}

If I remember correctly, that's correct C++ but incorrect C, even if
putSomethingThere() put "abc" into s, right?
 
K

Keith Thompson

C. J. Clegg said:
Consider this code:

char* s;
char* putSomethingThere( void );

s = putSomethingThere( );

if( s == "abc" )
{
...
}

If I remember correctly, that's correct C++ but incorrect C, even if
putSomethingThere() put "abc" into s, right?

The comp.lang.c FAQ is at <http://www.c-faq.com/>. You've just asked
question 8.2.

<OFFTOPIC>
The above code probably means the same thing in C++ as it does in C,
but C++ has other features that let you use the "==" operator to
compare strings. For details, consult a C++ textbook; if that fails,
ask in comp.lang.c++.
</OFFTOPIC>
 
D

Default User

C. J. Clegg said:
Consider this code:

char* s;
char* putSomethingThere( void );

s = putSomethingThere( );

if( s == "abc" )
{
...
}

If I remember correctly, that's correct C++ but incorrect C, even if
putSomethingThere() put "abc" into s, right?

You'll have to define what you mean by "correct". There are no syntax
errors that I see, although the definition for putSomethingThere() is
missing. However, comparing strings with == is almost always a design
flaw, as you will be comparing the pointer values, not what they point
to. It's the same for C++, although you might be thinking of the
std::string class.




Brian
 
C

C. J. Clegg

You may be thinking in C++ of the std::string class which AFAIR has an
== operator defined on it to permit comparison to a string literal.

Indeed, that's what I was thinking of. I forgot that C++ had an
overloaded == operator to permit that.

Thanks to all...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top