i need to share some strings in my c++ program. should i use #define or const string? thanks
mystring1.h
#define str1 "str1" #define str2 "str2"
Or
mystring2.h
extern const string str1; extern const string str2;
mystring.cpp
const string str1 = "str1"; const string str2 = "str2";
Const is a wrapper for strings that can only be created from program constants (i.e., string literals).
Answer. Character Constants are written by enclosing a character within a pair of single quotes. String Constants are written by enclosing a set of characters within a pair of double quotes.
You use the const keyword to declare a constant field or a constant local. Constant fields and locals aren't variables and may not be modified. Constants can be numbers, Boolean values, strings, or a null reference. Don't create a constant to represent information that you expect to change at any time.
The value of a variable can change depending on the conditions. In constants, the value cannot be changed. Typically, it uses int, float, char, string, double, etc. data types in a program.
Prefer the second option. If you use the first option (preprocessor), you are limiting your flexibility with the object.
Consider the following... You won't be able to compare strings this way:
if (str1 == "some string") { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With