Related
I have seen that even if you don't add std:: before stoi(s.substr(3,4)) (where s="123456789") it works fine, and also if you write std::stoi(s.substr(3,4)) the result is the same. So, is writing it like std::stoi(s.substr(3,4)) mandatory, or is it just good practice?
std::string s = "123456789";
int ans = stoi(s.substr(3,4));
std::cout<<ans;
std::string s = "123456789";
int ans = std::stoi(s.substr(3,4));
std::cout<<ans;
Both gives the same answer. And also sometimes writing std::stoi(s.substr(3,4)); gives an error.
It compiles without std:: because of the argument-dependent lookup.
I say it's a good practice to use std::stoi because:
It's more obvious that a standard function is being called.
It will not break if someone defines a variable named stoi prior to your code. This can be fixed by adding using std::stoi;, but since you call it once, it's more verbose than calling std::stoi directly.
It is considered good practice to add std:: namespace, so you can avoid conflicts if you use different libraries etc.
The probable reason it gives you an error sometimes is because you probably don't include the string header of the standard library:
#include <string>
but it is difficult without seeing the error, so please provide the details
Likely, if you can use stoi and get the same result as std::stoi, you might be using namespace std already.
This is not always desirable, depending on the project philosophy and the rest of your code suggests that you shouldn't depend on it.
edit: in this case, OP does not use using namespace std and something more subtle is going on (thanks #HolyBlackCat).
stoi() exists in the std namespace, so using stoi() without std:: works if there is a preceding using namespace std; or using std::stoi; statement, or when passing in a std::string object as an argument value due to Argument-Dependent Lookup (since string and stoi() are in the same namespace).
What is the cost of defining namespaces in c++? By that I specifically mean compile-time/run-time increase, and/or memory footprint. Let's say I have trivial program with a header file and a .cpp with main. Would I notice a change in these aforementioned statistics if I, say, define a namespace in my header? What about 10, 100, or 1,000 namespaces? What if they are defined but never used: does that change the answer? I guess you could say I'm curious how this construct interacts with the compiler(s).
Similarly, I am curious about the effect of struct/class definitions and using, but I couldn't think of a good title for a question encompassing all three.
What is the cost of defining namespaces in c++?
You have to write longer names†. This cost is offset by the fact that name conflicts are avoided across different namespaces. A short name is of no use if the name has a conflict.
†Not really though: A namespace lets you get off with less writing, since you don't always need to retype the namespace into unqualified identifiers.
By that I specifically mean compile-time
Potentially marginally.
run-time increase
None in practice.
Would I notice a change in these aforementioned statistics if I, say, define a namespace in my header?
You can find out by measuring.
You probably won't notice.
By that I specifically mean compile-time
Namespace can significantly reduce compile times since the compiler may have less overload to check when using a function.
This advantage is lost when using using namespace xyz;
Further compile time improvement can be done by using friend functions instead of free function, since ADL will have even less overload to check (in case of operators or if you already were using ADL)
I can't help it, but here is a real-life (although anecdotal) example of real cost of namespaces.
Several years ago I was working in a major company with very strong technological presence (no more would be said about them here). One of the distinctive aspects of their codebase was that it was dominantly server-side, Unix binaries compiled in 32 bit mode. One of the coding conventions used in the company was that every name should have been put in 3 nested namespaces - the rather long company name namespace, followed by 3 character name namespace, and than another one of 5 characters. (There were exceptions for legacy code).
The codebase was huge (as in linking of the executable would take up to 15 minute on a very powerful machine) and they were coming to the natural limit of executable size for 32 bit. Coming quickly - the new code was added, and the doom limit approached. A lot of solutions were discussed in a fire-sale urgency mode, and the one was that if we just used the shorthand for company name in the namespace, and may be used less characters in nested namespaces, we would postpone the doom of 32 bit limitation by several months!
Full disclosure - I do not know how this sutuation was resolved, I left the company before doomsday.
This question already has answers here:
Variable Naming Conventions in C++
(12 answers)
Closed 9 years ago.
In many examples of code that I've seen, they name their variable in a specific way.
E.g.
class obj
{
int mInt;
}
or
bool gTexture;
Questions.
Why do they name them in such way, and there are for sure more ways, I think...
How do you name them, and why?
Thank You
The m in mInt represents that the int is a member variable, while the g in gTexture denotes the variable being global.
This comes from Hungarian Notation.
http://en.wikipedia.org/wiki/Hungarian_notation
Naming is personally. To answer your second question, I don't use such a naming convention, and I append an underscore to class attributes.
Companies have often naming conventions. You may want to have alook at Google's naming conventions: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#General_Naming_Rules
The example you have given uses 'm' for member varibles and 'g' for globals. This is something that is used by some people. It makes it easy to see in a member function (when the function is a bit larger than a few lines, so you can't just look up at the top of the function to see the name of the parameters, local variables and so on), what is "local variable" and what affects "outside of the function".
If you work for a company, in a school or on an open source project, most likely, there is a coding standard that tells what the naming convention is. If it's your personal project, then decide on something you think works for you. The main point is that it's consistent. If not ALL member variables start with 'm', and not all global variables start with 'g', then it's pretty pointless to have it some places - just gives a false sense of security.
You haven't to follow a specific notation but it's cool if you do.
All is about clarity of your code, a variable without any upper case is truly less understandable than a variable with a good synthax. (At the first view, when you look quickly a part of code)
For a clear code, I can recommend the google's norme for c++ code : http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
Why do they name them in such way, and there are for sure more ways, I think...
Generally it is difficult to understand other people's code; If enough time passes, it is difficult to understand your own code as well.
Because of this, software teams set up conventions to make sure the code their team writes is as similar as possible to the code they themselves would have written.
This refers to structuring code, used elements (interfaces, classes, namespaces, etc), naming functions and variables, what to document and in which format, and so on.
When done properly and consistently, it has a significant effect of shortening code maintenance time within a team.
There are a few known conventions, mostly from the conventions used in implementing large code bases and used libraries.
Java tends to use camelCaseNotation (start with small letter, use no underscores, capitalize each word).
MFC used the Hungarian notation, where variable names are prefixed with a few letters specifying scope and type of data (m_XXX for member variables, g_XXX for globals, s_XXX for statics, etc).
In particular the Hungarian convention can be gotten right (by using prefixes for semantic information) or horribly wrong (by using prefixes for syntactical information).
(MFC got it horribly wrong.)
ANSI C++ (and std:: namespace) tends to use small_letters_with_underscores for identifiers.
There are others and most software teams set up a convention that is a variation of one of the big ones.
How do you name them, and why?
These days I follow the ANSI C++ conventions, mostly because I want my code to integrate seamlessly with library code. I also think it looks simple and obvious (and this is very subjective).
I rarely use one letter variables (only when the meaning is clear) and prefer full words, to shortened ones.
Examples:
indexes: int index, line_index, col_index;
class names: class recordset; class task_details; etc.
http://en.wikipedia.org/wiki/Hungarian_notation
Not a real question. Everyone name them as they want to. You may read these guidelines, though: http://msdn.microsoft.com/en-us/library/vstudio/ms229045(v=vs.100).aspx
The example below gets the following compiled error:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:26:8: error: no match for call to ‘(Derived) (p1&)’
test.cpp:14:8: note: candidate is:
test.cpp:16:10: note: void Derived::operator()(const p2&)
test.cpp:16:10: note: no known conversion for argument 1 from ‘p1’ to ‘const p2&’
It was my understanding this was getting changed in C++11 so you weren't required to put the using statement in. Is that not correct? Is there some other way around this?
Example (Compiled with gcc 4.7 using --std=c++11):
#include <iostream>
#include <string>
using namespace std;
struct p1{};
struct p2{};
struct Base
{
void operator()(const p1&) { cout << "p1" << endl; }
};
struct Derived : public Base
{
void operator()(const p2&) { cout << "p2" << endl; }
//Works if I include: using Base::operator();
};
int main(int argc, char** argv)
{
p1 p;
p2 pp;
Derived d;
d(p);
d(pp);
}
To the best of my knowledge, no, this has not changed in C++11.
And the reason it has not changed is that this behavior is not an accident. The language works like this by design. There are advantages and disadvantages to it, but it's not something that just happened because the people on the standards committee forgot about it.
And no, there's no way around it. It's just how member lookup works in C++
It was my understanding this was getting changed in C++11 so you weren't required to put the using statement in. Is that not correct?
No, member functions can still be hidden in C++11.
Is there some other way around this?
Using declarations are the intended remedy.
Just to clarify the situation: I can't imagine this ever changing in C++. To even hope to make it a tenable change, you'd have to tighten up type safety to the point that it would no longer be compatible with C (e.g., you'd pretty much have to eliminate all implicit conversions).
The situation is fairly simple: right now, name lookup stops at the first scope found that includes at least one instance of the name being used. If that instance of the name doesn't match the way you tried to use the name, then compilation fails.
Consider the obvious alternative: instead of stopping searching at that point, the compiler continues searching out scopes, created essentially an overload set of all those names, and then picked the one that matched the best.
In a case like this, a seemingly trivial change at an outer scope could (completely) change the meaning of some code, quite unintentionally. Consider something like this, for example:
int i;
int main() {
long i;
i = 1;
std::cout << i;
return 0;
}
Under the current rules, the meaning of this is clear and unequivocal: the i=1; assigns the value 1 to the i defined local to main.
Under the revised rules, that would be open to question -- in fact, it probably shouldn't be the case. The compiler would find both instances of i, and since 1 has type int, it should probably be matched up with the global i instead. When we print out i, the compiler finds an overload that takes a long, so it prints out the local i (which still contains garbage).
Note that this adds another wrinkle though: the cout << i; would be referring to the local i because there was an overload that could work with it. So instead of the type of the variable controlling the overload that was used, you'd have the available overloads also controlling the variable that was used. I'm not sure, but I'd guess this makes parsing much more difficult (quite possibly an NP-hard or NP-complete problem).
In short, any code that (intentionally or otherwise) used almost any kind of implicit conversion at an inner scope, this seemingly unrelated changes at outer scopes could suddenly change the meaning of that code completely -- and as in the example above, easily break it quite thoroughly in the process.
In the case above, with only a half dozen lines of code, it's pretty easy to figure out what's going on. Consider, however, what happens when (for example) you define a class in a header, then include that header into some other file -- the compiler looks at the other code where you included the header, find a better match, and suddenly code you swore was thoroughly vetted and tested breaks most spectacularly.
With headers, it would (or at least could) get even worse though. You define your class, and include the header into two different files. One of those files defines a variable, function, etc. at outer scope and the other doesn't. Now code in one file using name X refers to the global, while code in the other file refers to the local, because the global doesn't happen to be visible in that file. This would completely break modularity, and render virtually all code completely broken (or at least breakable).
Of course, there would be other possibilities that might not be quite this broken. One possibility would be to eliminate all implicit conversions, so only a perfect type match would ever be considered. This would eliminate most of the obvious problems, but only at the expense of completely breaking compatibility with C (not to mention probably making a lot of programmers quite unhappy). Another possibility would be to search like it does now, stopping at the first scope where it found a match -- then continuing to outer scopes if and only if compilation was going to fail if it used that name at the inner scope.
Either of these could work, but (at the very least) you'd need quite a few restrictions to keep them from leading to almost insane levels of confusion. Just for example, consider something like a =1; a = '\2'; Right now, those must refer to the same variable -- but with the first of these rules, they wouldn't.
With some special cases, you could probably eliminate that particular oddity too -- for example, use the current rules for looking up variable names, and new/separate rules only for function names.
Summary: the simple/obvious way to do this would create a language that was almost irretrievably broken. Modifications to prevent that would be possible, but only at the expense of throwing away compatibility with both C and essentially all existing C++ code. The latter might be possible in a brand new language, but for a language that's already well established like C++ (especially on that became established largely based on backward compatibility -- C++ again).
In my header, I have a prototype declaration like this:
void move(int, int);
I can omit the parameter names, that's how I'm used to it from C. I do that so that I don't have to keep the parameter names in sync - it's extremely confusing if they differ between prototype and implementation.
Right now, I'm documenting all of my code with Doxygen, and I decided to put all comments into the header. Now I have to refer to parameter names that are defined in the implementation but not in the header: I find that confusing.
/**
* Moves the entity to the specified point.
* #param x The x coordinate of the new position.
* #param y The y coordinate of the new position.
*/
void move(int, int);
In the generated Doxygen HTML, it is not easy to figure out which parameter is which. Of course, one could follow the same order here, but if one has many parameters, it is still confusing.
The alternative would be to duplicate parameter names and try to keep them in sync. However, some people don't encourage this approach, saying that header parameters should start with a double underscore so that the user of a method can not possibly use the same name (names starting with __ are disallowed in C++).
How do you do it?
It is a terrible idea to not name the parameters in the header if it is not clear what that parameter is for. The header should be the documentation for your code, so that someone trying to use it can avoid reading the implementation. As you found, it's pointless to document the parameters by name and then not tell the user which is which. That's not to say that they must match, but in the header they should be meaningful for the users of your code. In the implementation, choose the name that is best for you. E.g. it would be totally feasible to have:
.h:
void move(int x, int y);
.cpp:
void move(int deltaX, int deltaY)
{
...
The only times that it would make sense (if you care about other programmers using your code) to elide the parameter names is when it is bone crushingly obvious what that parameter does. E.g.
void SetNumPotatoes(int);
void EnableLights(bool);
void InitFoo(Foo&);
// but then...
T& GetItem(int); // probably obvious enough, but does typing 'index' kill you?
void DoSomething(bool, float, int); // someone using this will say, "WTF?"
Surely if "names starting with __ are disallowed in C++", you shouldn't be using them in prototypes either :-) *a
I see two ways to do it.
One, you can ensure that the order of parameters in your comments always matches the order in your prototype.
Or, two, you could actually put the real names in your prototypes as well.
Myself, I prefer the second approach since I like to be able to tell what parameters are passed in, even if the function has no comments on it (or worse, the comments get out of date). This is far easier with a prototype like:
void move(int xcoord, int ycoord);
than it is with:
void move(int, int);
In some environments, we've even gone so far as to have the build process ensure that all function prototypes have identically named parameters as the function definition.
*a) These identifiers are actually not for the use of regular programs. Section 17.6.3.3.2 of cpp0x (but this restriction has been around for quite a while in both C and C++) states:
Certain sets of names and function signatures are always reserved to the implementation:
Each name that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.
Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
In other words, don't use them for your own purposes.
They don't need to match, but I find parameter names to be invaluable documentation. I hate it when they're missing. I like in-code documentation far better than documentation in comments.
And the advice at the end of that link is really silly. Parameter names are nothing special as far as being in danger of being redefined by a #define. Function names and practically any other identifier in your header are in danger as well. That's why the naming convention of using ALL_UPPERCASE for your #define names exists.
No, make the names match in your implementation and in your header, even though the compiler will be fine if they don't. And if they don't match, fix it so they do. They provide excellent documentation and they will be confusing if they don't match.
WRONG documentation/parameter names is ALWAYS WORSE than NO documentation/parameter names. I'm not saying you don't need documentation or parameter names - I'm saying that you better keep up with them! That's why they pay us the big $$$ :-D
I always use parameter names both in header and in implementation. It is not difficult to keep them in sync - when I change the function parameters, I usually:
* Add/remove a parameter (no problem here - you have to sync it even if you didn't use parameter names)
* Change the order to be more logical (again, even the types have to be synced)
The advantage of having the parameter names in both prototype and implementation is that it helps the user - he can see the names in his IDE code completion, he doesn't have to navigate to the definition (which might be unavailable) to find out the parameter names. Another good reason for sticking to this practice is your Doxygen problem.
I also don't really see the point of using double underscores in prototype parameters. Yes, #defines are evil, but double underscores are reserved for compiler writers. Unless you write a standard header for your compiler, you should avoid it.
C and C++ are the same in this regard. The prototype names don't need to match up… that's why they may be omitted.
Pick names for the parameters; when you put them in Doxygen they become part of your API. You can change them later, but you're changing the API; you can change them in the implementation as well but then it won't match the spec as cleanly.
Do not use a double underscore, even for "ignored" identifiers. The compiler may define anything beginning with double underscore to mean anything, potentially causing a syntax error. Such words aren't just forbidden for names of in-scope variables, they are completely toxic.
If the header file belongs to an OEM library which is expected to be used by many third party vendors, inquisitive developers (such as those belonging to SO), will most certainly explore the header files in addition to the supplied documentation, given the fact that most of the time documentation is either very bad or lags significantly behind the code.
Therefore, I would say, the issues cited about the naming the parameters could be a development time pain, but is almost certainly a customer's delight.
What is protype declaration is that you are informing compiler that this type of function is going to come with this arguments and with this data types. So compiler will make arrangemnts for that type of arguments.
hence proto data type and number of arguments should match with the actual definition and run time usage.
Otherwise it will give an run time error.