why this code giver error in visual studio on the other hand it works fine in code blocks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

void disp(char *c) //here visual studio says it should be "const char *c"
{
    using namespace std;
    cout << "name is : " << c << endl;
}
int main(void)
{
    disp("Hello World \n ");
    cin.get();
    return 0;
}
Last edited on
Visual Studio is correct.

"Hello World \n " is a string literal and is const (because you can't change it). It has type const char *.


If you want the ability for disp() to display non-const sequences (i.e. char *, without the const) then you will have to put your text in a variable char array. In the following, mystring is initialised to "Hello World \n", but it is not const, and could be changed by other statements.

Try this and your original code in c++ shell.

(Oh, and please use code tags.)

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

void disp(char *c)
{
   cout << "name is : " << c << endl;
}

int main()
{
   char mystring[] = "Hello World \n";
   disp( mystring );
}


Some compilers allow your version, a few with a warning (including cpp shell), but it would appear to be a legacy programming concession.
Last edited on
> "Hello World \n " is a string literal and is const (because you can't change it). It has type const char *

The type of the literal "Hello World \n " is 'array of 15 const char'

1
2
3
4
5
6
#include <iostream>

int main()
{
    std::cout << sizeof( "Hello World \n " ) << '\n' ; // 15
}

http://coliru.stacked-crooked.com/a/2d38232f70d33d36
Thank you lastchance for your reply actually i am new to the forum community , next time i'll remember your suggestion about code tag .
https://en.cppreference.com/w/cpp/language/string_literal

OK: string literal type is
const char[]
not
const char *

I guess there are some small differences between C and C++ as well:
In C, string literals are of type char[], and can be assigned directly to a (non-const) char*. C++03 allowed it as well (but deprecated it, as literals are const in C++). C++11 no longer allows such assignments without a cast.
Topic archived. No new replies allowed.