interesting!

Hello.
suppose I have a declaration:
char *s="";

Now the statement:
cout << !(*s);

couts 1(true);while
cout << *s;
prints nothing;Not even 0(false).Why is it so?

Thanks in advance!

because *s is a char which is 0. If the stream detects a 0 char it doesn't print anything
1
2
3
4
5
6
7
// char* s = "" ; //  *** warning: deprecated conversion *** AVOID
const char* s = "" ;
std::cout << std::boolalpha
          << !s // true (converted to bool)
          << bool(s) // false (converted to bool)
          << s // nothing (no conversion, just an empty C string)
          << '\n' ;
I wonder why it is possible to dereference s without generating an error ?

Well my guess is that if you write something like char *s = "c", the compiler changes this to something like

1
2
char tmp = 'c';
char *s = &tmp;


And by the way, when im compiling this with g++ i get the following warning:


warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
I wonder why it is possible to dereference s without generating an error ?

s is a pointer so why would it not be possible to dereference it?
@AleaIactaEst
Well my guess is that if you write something like char *s = "c", the compiler changes this to something like

char tmp = 'c';
char *s = &tmp;



"c" (in double quotes) is a string literal. It is represented in memory as

const char tmp[] = { 'c', '\0' };

and s will be correctly defined as

const char *s = tmp;

sizeof( "c" ) is equal to 2 not 1, while sizeof( 'c' ) is equal to 1 because 'c' is a character literal.
Because i do not see why s should point to anything but NULL (or nullptr), except if char *s = "c" behaves like i have written above.
As I already described

const char *s = "";

is equivalent to

const char tmp[] = { '\0' };
const char *s = tmp;

So s points to a memory cell that contains a single symbol '\0'. This cell has an address different from 0.
Ok that's clear now, but i dont understand why you insist on writing const char* s instead of char* s. s is not a const pointer after all (see definition in first post by hooshdar3)
Because the C/C++ standards supress to change string literals. The compiler may place string literals in the read-only memory. Moreover depending on compiler options it can place two string literals with the same contents either in the same location or in different locations. So it can be that

the result of expression "Hello" == "Hello" will be either true or false depending on options of the compiler.

I gave an answer to a similar question here
http://cpp.forum24.ru/?1-1-0-00000002-000-0-0-1343475536
Though it is written in Russia you can use google translate to read the thread. It is named as "A string literal and a pointer to a string: what is the difference."
Last edited on
влад!
Please always posts in english.Google translator is not a good translator!
Topic archived. No new replies allowed.