ArthurTheLearner
ArthurTheLearner

Reputation: 315

How to define an array of strings and set its values in header files in C++?

In my program, I use constants defined through the #define directive in order to manage the program's logic. At the same time, if I need to print one of these values, I need some way to map these numbers with a string.

Here is a simplified version of what I'm attempting:

Header file: header.hpp

#ifndef HEADER_HPP
#define HEADER_HPP

#include <string>

#define CODE_0 0
#define CODE_1 1
#define CODE_2 2
#define CODE_3 3

std::string label[4];
label[CODE_0] = "label0";
label[CODE_1] = "label1";
label[CODE_2] = "label2";
label[CODE_3] = "label3";

#endif /* HEADER_HPP */

Main function: source.cpp

#include "header.hpp"
#include <iostream>

int main()
{
  std::cout << "Start" << std::endl;
  std::cout << "Code #" << CODE_1 << " has label '" << label[CODE_1] << "'" << std::endl;
  std::cout << "End" << std::endl;

  return 0;
}

However, this doesn't work. Here's the compiler output:

In file included from source.cpp:1:0:
header.hpp:12:1: error: 'label' does not name a type
 label[CODE_0] = "label0";
 ^
header.hpp:13:1: error: 'label' does not name a type
 label[CODE_1] = "label1";
 ^
header.hpp:14:1: error: 'label' does not name a type
 label[CODE_2] = "label2";
 ^
header.hpp:15:1: error: 'label' does not name a type
 label[CODE_3] = "label3";
 ^

I'm not sure why this is happening. It looks like this isn't the way to set the array's values. What would be the correct way?

Also, although it is a different question, what would be a better way to map these constant numeric values to their respective strings? Notice that I intend them to remain constant (both number and string).

Upvotes: 0

Views: 1342

Answers (1)

user7860670
user7860670

Reputation: 37513

You can initialize this array in header file without explicit assignment statements:

std::string label[4] =
{
    "label0"
,   "label1"
,   "label2"
,   "label3"
};

The better approach would be to get rid of it completely or at least make it class static variable and define in cpp file. Also it would be better to replace #define CODE_0 macroses with enumerator.

Upvotes: 1

Related Questions