Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const string vs. #define

Tags:

c++

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"; 
like image 282
user612308 Avatar asked Apr 04 '11 23:04

user612308


People also ask

Can a string be const?

Const is a wrapper for strings that can only be created from program constants (i.e., string literals).

What is the difference between string and constant?

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.

What is a const string in C#?

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.

What is difference between string constant and string variable?

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.


1 Answers

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") {     // ... } 
like image 100
Marlon Avatar answered Sep 20 '22 18:09

Marlon