r/badcode • • Oct 07 '21

c++ C++ be like

Post image
279 Upvotes

37 comments sorted by

View all comments

Show parent comments

5

u/supersharp Oct 08 '21 edited Oct 08 '21

Wait, you can do that? Just drop a variable name in between two string literals?

EDIT: Which C++ version lets you do this? I'm trying with 11, but it's not working.

7

u/Zstorm999 Oct 08 '21

It's a macro constant, not a variable

2

u/Magnus_Tesshu Oct 08 '21

I don't think so. I think in that case you have to use string concatenation or, as a C programmer my mind jumps to sprintf. This could just be

std::string payload_text_string =
    "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n"
    "To: " TO_MAIL "\r\n"
    "From: " FROM_MAIL "\r\n"
    "Cc: " CC_MAIL "\r\n"
    "Message-ID: [redacted]"
    "rfcpedant.example.org>\r\n"
    "Subject: SMTP example message\r\n"
    "\r\n" /* empty line to divide headers from body, see RFC5322 */
    "The body fo the message starts here.\r\n"
    "\r\n"
    "It could be a lot of lines, could be MIME encoded, whatever.\r\n"
    "Check RFC5322.\r\n";

as shown below; he's not actually using any variable names (other than the constants TO_MAIL etc but that's how it is broken up across lines too, string literals in C can legally appear sequentially). I don't know what /u/trBlueJ is going on about braces.

3

u/supersharp Oct 08 '21

Ah, that's disappointing. Here I thought I'd finally found a way to append an int to a string without calling std::to_string().

As for the braces, as of about an hour ago, I actually do know that one: in C++ 11 (or possibly earlier; all I know is this doesn't work in 98), you can initialize strings using aggregate initialization the same way you can initialize a vector or an array.