Prototype parameter names - c++

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.

Related

Why is it not allowed to have default arguments on function declaration and definition?

so why is it not allowed to have default arguments on the function declaration and implementation? Wouldnt this be more readable for the implementer and the user of the function?
Is there a special reason why this is not allowed, or why the compiler or linker cant handle this?
Best regards
In fact, it is just that we cannot have, in the same scope, 2 declarations with a (common parameter with a) default argument:
void foo(int = 42);
void foo(int = 42); // Error.
and definition acts also as declaration.
if your definition doesn't include the header with the declaration,
you might have default in definition too.
Notice that default is not part of the signature, but should anyway is the same (by scope) for each translation unit (for inline functions, and also for non-inline functions since C++20 (but some default can be omitted)).
I don't know the why of those rules though.
There is no real reason except that the committee decided so and they apparently like to show their power by torturing millions of programmers this way.
Ok... may be this is not true but in my opinion it's a more logical explanation of why this is forbidden that anything I've read about the issue.
Note that g++ with -fpermissive allows default to be specified both in declaration and in implementation IF THE VALUES ARE THE SAME and gives an error if they are different.
This is the way IMO it should be in the standard, but it's not.
Because no.
PS: Don'y try to read too much into logical reasons about the rules of C++. Many times there are reasons, sometimes there are just poor justifications of a sad incident that must stay in forever for backward compatibility, sometimes there is no reason at all... it's just the way it is. This, added to the complexity of C++ and the concept of Undefined Behavior, is in my opinion why experimenting with C++ doesn't work well and you need to actually read the standard rules. Being smart doesn't help if you're experimenting, because the "correct" answer is often the wrong one. There's no way you can guess what was the decision taken in that rainy day at the committee meeting.

How can I declare variables with illegal names (such as "int double = 0")?

I have tried to do this but I'm unable. How can i declare a number of variables with legal and illegal names (such as int double = 0;), so that you can see how the compiler reacts.
The short answer to this is DON'T DO IT.
There are a number of reserved words in the C and C++ standards that should not be used for any purpose other than which they are originally intended. Going out of your way to recycle these for your own perverse purpose is going to create problems for a lot of people. One of those people might be yourself fin the future when you have to fix a bug.
If you want to use double as a variable name, the best method to make this happen is to successfully petition the C++ committee constructing the next standard to allow it. Then you will have a valid program.
If you want to see how the compiler behaves when encountering this problem, create tiny programs that are as small as practical. For example:
// invalid_double.c
int double = 0;
You'll immediately see a syntax error when trying to compile that. Repeat as necessary with other keywords. This is often how things like configure run tests to verify the behaviour and capabilities of the local compiler.
Your compiler will probably halt compilation at the first invalid use of a keyword so you may need to construct one file per experiment. Subsequent errors in the same file may be ignored, such as if you had int class = 0
it is like a Quote from (Programming__Principles_and_Practice_Using C++),I think the auther asks us to try it and see the error no more(just we try it ourselfes).

C++ Naming variables [duplicate]

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

Why do function prototypes include parameter names when they're not required?

I always thought that a function prototype must contain the parameters of the function and their names. However, I just tried this out:
int add(int,int);
int main()
{
std::cout << add(3,1) << std::endl;
}
int add(int x, int y)
{
return x + y;
}
And it worked! I even tried compiling with extreme over-caution:
g++ -W -Wall -Werror -pedantic test.cpp
And it still worked. So my question is, if you don't need parameter names in function prototypes, why is it so common to do so? Is there any purpose to this? Does it have something to do with the signature of the function?
No, these are not necessary, and are mostly ignored by the compiler. You can even give them different names in different declarations; the following is entirely legal:
int foo(int bar);
int foo(int biz);
int foo(int qux) {
...
}
(The compiler does check that each name is used only once in the same argument list: int foo(int bar, int bar); is rejected.)
The reason to put them in is documentation:
If someone reads your header file, they can tell at a glance what each parameter is used for.
If you use a fancy IDE, it can show you the parameter names when you begin typing the function call.
Documentation tools like Doxygen can parse the parameter names and show them in the documentation.
Parameter names are completely optional, and have no effect on compilation. They may be placed there for better readability of code.
You don't need parameter names in declarations. They are purely documentation.
You don't even need names in definitions:
int f(int)
{
return 0;
}
compiles just fine in C++ (though not in C). This is sometimes useful for e.g. inheritance, overloading, function pointers.
You do not need to include parameter names in function prototypes. You only need the complete signature, which includes the types of parameters and (in the case of function template specializations) return values.
However, it is still common to include parameter names in order to write self-documenting code. That is, a function with this declaration:
void foo(int number_of_foos_desired, string foo_replacement);
is easier to understand by looking only at the prototype, perhaps, than this one:
void foo(int, string);
Many modern IDEs will also pop up the parameter names as you type when you write code that calls this function. They may not be able to pop up this information if you dont include the parameter names in the prototype.
It has alot to do with the signature of the function.
One of the benefits of using .h files is that when someone comes along and wants to get a sense of what your program/api does, they can look at your header file and get a sense of what operations are being carried out, their inputs and outputs, how everything is going together, etc.
If you were to come across a method like
int doStuff(int,int)
this would be alot less telling than a method with a signature of say:
int doStuff(int firstNumberToAdd, int secondNumberToAdd);
with the second, you at least get some idea of the operations that are being carried out, and what is happening. This is the idea behind writing self documenting code.
If your interested, you may check out Code Complete by Steve McConnell.
There are different scenarios to it. I found it very helpful in dealing with inheritance and virtual functions. If you're using a virtual function that generates unused warning in sub class, you can omit the variable names.

C++ class function in assembly

Hello Community
I am look at C++ assembly, I have compiled a benchmark from the PARSEC suite and I am having difficulty knowing how do they name the class attribute functions in assembly language. for example if I have a class with some functions to manipulate it, in cpp we call them like test.increment();
After some investigation I found out that this function is
atomic_load_acq_ptr
represented as:
_ZL19atomic_load_acq_intPVj
in assembly, or at least this is what I have found out.
Let me know if I am wrong!
Is there some fixed rule for the mapping? or are they random?
Thanks
It's called name mangling, is necessary because of overloads and templates and such (i.e. the plain chars-and-numbers name isn't enough to identify a chunk of code unambiguously; embedding spaces or <> or :: in names usually isn't legal; copying the additional information in uncondensed, human-readable form would be wasteful), and it therefore depends on types, arity, etc.
The exact scheme can vary, but usually each compiler is self-consistent for a relatively long time (sometimes even several compilers can settle for one way).
That's called name mangling.. It is compiler dependant. No standard way, sorry :)
C++ allows function overloading, this means that one can have two functions with the same name but different parameters. Since your binary formats do not understand type this is a proble. The way that this is worked around is to use a scheme called name mangling. This adds a whole function of type information to the name used in the source file and ensures one calls the correct overload.
The extra letters etc that are added are governed by the particular Application Binary Interface (ABI) being used. Different compilers (and sometimes even different versions) may use different ABIs.
Yes there's a standard method for creating these symbols known as name mangling.