-4

following code is

void main(void)
{
    char* p = "presp";
    
    p = "456"+1;                 /*----> makes error*/
    p = p + 1;                  /*----> does not make error*/
    
    printf("%s", p);            /* ----> (wanna make '56')*/
}

I'M CONFUSING THE DIFFERENCE BETWEEN THOSE TWO LINES. IS IT JUST BECAUSE I'M USING C++ PROGRAM OR THERE IS KIND OF DIFFERENCE BETWEEN TWO. PLEASE HELP ME...

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
  • What are you trying to accomplish with the failing line and what do you expect it to do? – Anon Mail Feb 28 '22 at 14:25
  • 4
    In C++ a string literal is `const` so your variable should be `const char* p` – UnholySheep Feb 28 '22 at 14:26
  • 1
    Actually, `char* p = "presp";` shouldn't work, because string literals are of type `const char[]` and can only decay to `const char *`, not `char *`. – Lukas-T Feb 28 '22 at 14:26
  • 2
    I think `char* p` is wrong. It should be `const char* p`. – The Coding Fox Feb 28 '22 at 14:26
  • 6
    Try this: `p = &1["456"];` But first, you should probably get yourself a [good C++ book](https://stackoverflow.com/a/388282/4641116). And enable your compiler warnings. – Eljay Feb 28 '22 at 14:26
  • Note that, although this code will (probably?) compile as C, it is not valid C++ for several reasons (not just the problem stated in the question). `void main(void)` is **not** a valid `main` definition in C++. – Adrian Mole Feb 28 '22 at 14:29
  • 4
    Please don't claim something "makes error" without showing what the error is. Why do we have to guess when you can easily copy and paste it? And PLEASE DON'T SHOUT. All-caps is harder to read and frankly rude. – Useless Feb 28 '22 at 14:36
  • Don't scream it :P – andreee Feb 28 '22 at 14:37
  • @AdrianMole For completeness: on *hosted* environment; on bare metal hardware the matter changes a bit... – Aconcagua Feb 28 '22 at 14:44
  • The difference is that `"presp"` is a string literal (and its type is `const char[6]`), but `"456"+1` isn't (and its type is `const char*`). – molbdnilo Feb 28 '22 at 14:49

1 Answers1

2

This actually works pretty fine – the error arises already earlier:

char* p = "presp";

String literals are actually arrays of char const, so assignment to a pointer to non-const is not conforming the standard.

This differs from C where literal indeed are arrays of non-const characters, though these still are immutable (so even in C you should as good practice assign literals only to pointers to const).

For compatibility reasons, though, a number of C++ compilers accept assignment of literals to pointers to non-const, usually issuing a warning (you absolutely should listen to). However by adding one, the array decays to a pointer and this exception doesn't apply any more.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59