I download many examples in C ++ and in some places there is char * ch = "string"; and the compiler always gives an error. I have a Visual Strudio 2017 community. Why is that?

#include <windows.h> #include <iostream> #include <conio.h> using namespace std; int main() { char* ch = "test"; return 0; } 
  • What mistake? How then describe in more detail what the problem is - Twiss
  • For C ++, add const - const char * = "text"; The fact is that the pointer really refers to a constant (such data cannot be changed, so the compiler reports this) - avp

2 answers 2

As far as I remember, in the latest versions of , the automatic application of const to the parameters of functions and variables (local), i.e., was abolished. if you defined a pointer to a string through

 char* ch = "string" // "string" это не char* а const char*; 

So, here, in essence, there should be a const_cast transformation about which I spoke above, which is no longer supported and the transformation lies with the developer.

  • For some reason, I thought so, because I still watch different video examples, and such records work on these videos, but I don’t. It turns out that libraries written initially with char * ch will not work in new versions of VS? - Dmitry Mizantropovich
  • There will be if you will use an older version of MVS. Or set in the compiler options the additional /-permissive parameter about which @Harry spoke. But it’s better not to do that, and just add const . - LLENN
  • Thanks found this flag earned, but I will stick to your advice in the future. - Dmitry Mizantropovich

This is an erroneous action, because a string literal of type "string" is actually a constant string that cannot be changed. It may well be placed in read-only memory.

And assigning it to a char* pointer formally allows you to change this string.

Only, unfortunately, VC ++ 2017 does not report any errors, and this assignment permits: (

Here, your program when compiling VC ++ 2017:

 cl /EHsc /W4 test.cpp Оптимизирующий компилятор Microsoft (R) C/C++ версии 19.13.26129 для x64 (C) Корпорация Майкрософт (Microsoft Corporation). Все права защищены. test.cpp test.cpp(8): warning C4189: ch: локальная переменная инициализирована, но не использована Microsoft (R) Incremental Linker Version 14.13.26129.0 Copyright (C) Microsoft Corporation. All rights reserved. /out:test.exe test.obj