I Just wanna know what happens if we try to do the following in C++: "abc"+'d'
i.e what happens if we concatenate a character to a C-string.

Recommended Answers

All 5 Replies

try it in a tiny program and you will find out. The best way to find out such things is to write a little program to test it yourself, you will learn a lot more that way.

As Ancient Dragon says, you should just try it an see.

On a related note, you can concatenate multiple C-strings like this:

#include <iostream>

int main()
{
    char s[] = "Hello" ", " "World!";
    std::cout << s << std::endl;

    return 0;
}

I don't know when it's useful, but you can do it. I guess if you had a really wrong string literal that you had to type out and you wanted to split it over multiple rows or something.

I Just wanna know what happens if we try to do the following in C++: "abc"+'d'

In that particular case, you'd overrun the "abc" array by indexing it beyond the null character at the end. However, whether this is a problem or not depends on how you use the result.

So what's happening? "abc" is converted to a pointer to the first element. Then 'd' is interpreted as an integer value and added to that pointer. The result is the same as any pointer arithmetic of the form p + n. But because "abc" doesn't have enough characters to handle pointer arithmetic beyond p + 3, and (int)'d' is surely much larger than that, you risk undefined behavior.

This is the test program you should have written:

#include <iostream>

int main()
{
    std::cout<< "abcdefg" + 4 <<'\n';
}

In that particular case, you'd overrun the "abc" array by indexing it beyond the null character at the end.

Not really. It flat won't work (compile errors) because they can't be concantinated like that.

It flat won't work (compile errors) because they can't be concantinated like that.

The left operand is a string literal and the right operand is a character literal. It will most certainly compile and run, because the character literal will be interpreted in integer context. Assuming ASCII for the sake of the example, the compiler will see "abc" + 100, which I'm sure you'll agree is both legal and highly error prone. While the address &"abc"[100] can be calculated, any attempt to access it will invoke undefined behavior.

If the right operator were also a string then it wouldn't compile because you'd be adding two pointers, which is not legal. I'm assuming that you just misread the question and saw both operands as string literals. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.