Vinodini Natrajan
Vinodini Natrajan

Reputation: 155

C++ runtime_exception with string + integer

In C++ I am throwing a run time exception like below,

throw std::runtime_error("abcdefghijklmnopqrstuvq"+12);

The exception that is thrown doesn't have the initial few characters.

terminate called after throwing an instance of 'std::runtime_error'
  what():  mnopqrstuvq
Aborted (core dumped)

Can someone explain this behavior ?

Things work fine if I use the below stmt to throw the exception

throw std::runtime_error("abcdefghijklmnopqrstuvq"+std::to_string(12));

Upvotes: 0

Views: 1003

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

One of the definitions for runtime_error takes a const char*, which is what you are passing it. This section of code:

"abcdefghijklmnopqrstuvq"+12

Takes the pointer to this const char* and increments it by 12 (which happens to be m in the string).

When you do this:

"abcdefghijklmnopqrstuvq"+std::to_string(12)

you are invoking the operator+(const char*, std::string) function which returns a string (specifically "abc...12"), thereby calling the runtime_error(std::string&) declaration.

Upvotes: 2

cigien
cigien

Reputation: 60238

The literal "abcdefghijklmnopqrstuvq" is actually just a pointer to an array of char const.

Adding 12 to it gives a pointer 12 positions ahead, which is "mnopqrstuvq".

Upvotes: 2

Related Questions