简体   繁体   中英

c++ best way to call function with const char* parameter type

what is the best way to call a function with the following declaration

string Extract(const char* pattern,const char* input);

i use

string str=Extract("something","input text");

is there a problem with this usage

should i use the following

char pattern[]="something";
char input[]="input";
//or use pointers with new operator and copy then free?

the both works but i like the first one but i want to know the best practice.

文字字符串(例如"something" )可以很好地用作函数调用的const char*参数。

Unless you plain to have duplicates of the same strings, or alter those strings, I'm a fan of the first way (passing the literals directly), it means less dotting about code to find what the parameters actually are, it also means less work in passing parameters.

Seeing as this is tagged for C++, passing the literals directly allows you to easily switch the function parameters to std::string with little effort.

The first method, ie passing them literally in, is usually preferable.

There are occasions though where you don't want your strings hard-coded into the text. In some ways you can say that, a bit like magic numbers, they are magic words / phrases. So you prefer to use constant identifier to store the values and pass those in instead.

This would happen often when:

  • 1 . a word has a special meaning, and is passed in many times in the code to have that meaning.

or

  • 2 . the word may be cryptic in some way and a constant identifier may be more descriptive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM