c style



1
2
3
4
5
char a= 'a';
cout« a «endl «&a
//why cout <<&b attempts to print a NTBS ?
const char * mtn = "hello";
//why must use a const to create hello! 
Last edited on
why cout <<&b attempts to print a NTBS ?


Lets with NTBS, you always pass a pointer to the first element, which is what you are doing here. cout thinks you are passing it a string array, like if you were doing this:

1
2
3
char a[] = "bob";
std::cout << a;        // Address of first element 
std::cout << &a[0]   // Your situation in the eyes of std::cout 


Both lines produce the same print. For more info, read this: http://www.cplusplus.com/doc/tutorial/ntcs/. There is some std::cout action with char arrays.

why must use a const to create hello!


It doesn't. This compiles:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
    {
    char * mtn = "hello";
    cout << mtn;

    return 0;
    }


and produces:
hello
Last edited on
To print the address of a character or string of characters, cast it to void *. The output stream has a built-in overload for type char* which by default treats it as a character string.
1
2
    char a = 'A';
    cout << (void *)  &a << '\n'; 


This line:
 
    char * mtn = "hello";
generates a warning,
[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]
because the literal "hello" is a constant, that is, it cannot be changed by the program code, hence the pointer should be declared as const in order to prevent that.

@aqayekhas: Like Chervil says, you get a warning. You can still go about it without the "const" and it will compile (no errors, only warnings) if you have basic compiler setup. However, it is good practice to consider warnings as errors.

As for the answer to your question -- why you get a warning -- I think Chervil sums it up pretty well.
Not only good practice to consider warnings as errors. Further, it is good practice to set the compiler to generate as many warnings as possible, as well as ask it to conform to the ISO standard. It may be tempting to consider messages issued by the compiler as obstacles, but I'd suggest that the compiler is there to help you, and asking it to provide as much help as possible is a good thing. If nothing else, it helps to avoid accidental or silly errors where one writes something unintentionally, and the compiler can nudge you back to what you really meant.

In the gnu compiler I use (at least)
-std=c++11 -Wextra -Wall -pedantic-errors
and may add -Werror to treat all warnings as errors.
Thanks to both of you
Topic archived. No new replies allowed.