1

I want to refactor:

const char* arr = 
  "The "
  "quick "
  "brown";

into something like:

const char* quick = "quick ";
const char* arr = 
  "The "
  quick
  "brown";

because the string "quick" is used is many other places. Ideally I need to be able to do this with just const primitive types, so no string. What is the best way to do this?

user3757652
  • 35
  • 1
  • 2
  • 6
  • 1
    Rarely the case is so, but a preprocessor macro would seem more appropriate. – WhozCraig Nov 07 '14 at 18:34
  • You can't reuse sub-strings. Each literal string has to be consecutive in memory. If you want to optimize memory usage, then you have to do it by code (i.e., during runtime). – barak manos Nov 07 '14 at 18:37
  • 1
    Or use std::string and concatenate them. I don't know if that has performance implications for you. – Neil Kirk Nov 07 '14 at 18:38
  • No performance issues but this is a global variable inside an anonymous namespace and it's company policy to have only primitive types outside classes/functions due to indeterminate initialization order. And I like to avoid macros when I can (eg here). – user3757652 Nov 07 '14 at 19:38

1 Answers1

4

Compiling the comments in the form of an answer:

  1. Use a macro.

    #define QUICK "quick "
    
    char const* arr = "The " QUICK "brown";
    
  2. Use std:string.

    std::string quick = "quick ";
    std::string arr = std::string("The ") + quick + "brown";
    

Working code:

#include <iostream>
#include <string>

#define QUICK "quick "

void test1()
{
   char const* arr = "The " QUICK "brown";
   std::cout << arr << std::endl;
}

void test2()
{
   std::string quick = "quick ";
   std::string arr = std::string("The ") + quick + "brown";
   std::cout << arr << std::endl;
}

int main()
{
   test1();
   test2();
}

Output:

The quick brown
The quick brown
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • I'm accepting this answer. I think I'll use string and hide it inside another function. I wish I can upvote everyone who contributed rather than the aggregator, but hey! that's how life works too. – user3757652 Nov 07 '14 at 19:39
  • Thanks for confirming that what I want to do can't be done, that was definitely very helpful. – user3757652 Nov 07 '14 at 19:40