Which is preferred: foo(void) or foo() in C++ - c++

I have seen two styles of defining conversion operator overload in C++,
operator int* (void) const
operator int*() const
Question 1. I think the two styles (whether add void or not) have the same function, correct?
Question 2. Any preference which is better?

This doesn't just apply to conversion operators but to all functions in C++ that take no parameters. Personally, I prefer to omit void for consistency.
The practice originates from C. Originally, when C did not have prototypes, an empty pair of braces was used in function declarations and did not provide any information about the parameters that the function expected.
When prototypes were added, empty braces were retained for function declarations to mean 'unspecified parameters' for flexibility and backwards compatibility. To provide an explicit prototype meaning 'takes no parameters', the syntax (void) was added.
In C++ all function declarations have to have prototypes, so () and (void) have the same meaning.

Quoting from ISO C++ FAQ, Should I use f(void) or f()?
C programmers often use f(void) when declaring a function that takes no parameters, however in C++ that is considered bad style. In fact, the f(void) style has been called an "abomination" by Bjarne Stroustrup, the creator of C++, Dennis Ritchie, the co-creator of C, and Doug McIlroy, head of the research department where Unix was born.
If you're writing C++ code, you should use f(). The f(void) style is legal in C++, but only to make it easier to compile C code.
Appeal to authority FTW :)

In C++ foo() and foo(void) are the same - "no arguments". In the C99 standard, the former means "undefined number of arguments", while the latter means "no arguments".
However, if you rely on the foo() behavior in C, you should be shot.
So this means that you can use either. Now personally, I like foo() better than foo(void), since I hate visual clutter, but that's just preference. I'm a Python guy :)

I believe in 'older' C (don't know what version) foo() meant 'any parameters' whereas foo(void) meant no parameters. foo() 'any parameters' version has been deprecated I believe in c99.
Quick googling finds this wikipedia article mentioning similar fact.
C++ will accept foo(void) but it means the same as foo() which means 'no parameters'.
So in C++ the preferred way is to use foo().

omit the void. In old style C all functions were assumed to be int name(...). Specifying void meant it was not a variable length parameter. That default was removed and all functions had to be specified (thankfully. It was the wild west when anything could be anything). In C++ you dont need to write (void) ever. Omit it. Just as the C++ libs do.

Related

Why is no argument in a function prototype preferred?

I have a question about coding style in C++.
I prefer to use void explicitly in function prototypes.
However, during reading an article about void type in Wikipedia, I have seen that giving no argument in a function prototype is preferred.
Why is no argument in the prototype preferred?
I am so curious if there is a specific reason.
C++ had function prototypes before C did, and C++ has 'always' required prototypes in effect. Therefore, there was no problem or ambiguity about empty brackets (parentheses) meaning no arguments.
By contrast, C did not acquire function prototypes until long after C++ had them, and it had a legacy base to deal with. Until function prototypes were introduced, C functions with non-integer return types had to be declared as:
double sin();
char *malloc(); /* There wasn't void * -- or C++ style // comments */
struct whatnot *new_whatnot();
The C standardization committee could not afford to break all the existing C code; the standard would have failed. So, the C standardizers adopted sometype function(void) to indicate explicitly 'no arguments'. To this day, sometype function() means 'a function returning a sometype value taking an undefined (but not variable) number of arguments of undefined type'.
Because C++ had the empty brackets (empty parentheses) notation, there was no need for the (void) notation, but it was added to C++ to match the C standard and make it easier to migrate code between standard C and C++.
Code written natively for C++ should use the native, empty brackets notation.
Code written natively for C must use the explicit (void) notation because the empty parentheses means something quite different (and relatively undesirable).
Code written to be migratable between C and C++ might use the explicit (void) notation to ensure that both compilers see the same specification.
What is prefered and what is a good practice are quite different. I believe that is just a choice of the programmer.

The standard C function declaration syntax (WINAPI) [duplicate]

This question already has answers here:
What does "WINAPI" in main function mean?
(4 answers)
Closed 7 years ago.
I know you might think this question already been answered but it is not, or at least it was not very clear to me.
int WINAPI WinMain (){}
This is a pseudo form of the famous winmain function.
My question is about the calling convention WINAPI, in particular its placement between the "return type" and the "function name". Is this Standard C? Because I referenced the Brian W. Kernighan and Dennis M. Ritchie book and I didn't see this form.
I also have searched for its meaning and they said it's a macro to place _stdcall instead. So please don't tell me the question is duplicated.
And here is one of the questions that might be very close to mine
What does "WINAPI" in main function mean?
I want a clear answer for this WINAPI: Is it standard C? So I can place a calling convention after the return type in any function declaration and I then give it to any C compiler in the world? Or is it something will work only on Microsoft compilers? And if so, can anyone impose their rules on the C syntax?
I'm sorry I know my question might be trivial for many of you, but I searched everywhere about the functions declaration syntax and all sources denied this calling convention place.
The essential answer: No. A function declaration, as defined by the C language standard, has no elements between the return type and the function name. So int __bootycall myFunc(int qux) is not standard C (or C++), even though C implementations are allowed to reserve __customIdentifiers for their own exclusive use.
However.
The need for calling-convention specifiers (e.g. __cdecl) is clear; a lot of (especially early non-UNIX [especially MS-DOS]) platforms had more than one calling convention to choose from, and specifying the calling convention of a function was as important as, if not more important than, the parameter list of that function. Hence the need to slot a little something extra in there.
At that time (even before C89), there was no provision made for architecture-specific function attributes (presumably because C, designed for the sole purpose of implementing UNIX utilities, didn't need any). This would later be remedied in C99, and if C99 had existed at that point, it's likely that __cdecl et al. would have been function attributes, not random identifiers shoved in there. But as it was, when the need arose to specify non-default calling conventions, there were four reasonable places to put it: Before the return type, between the return type and the function name, between the function name and the opening parenthesis of the argument list, and after the argument list.
I'm speculating here, but it seems like the second option would have made the most sense. This was pre-C++, remember; there was no post-arglist-const, and the only thing that could show up before the return type was static, which specified linkage rather than anything about the function per se. That left before or after the function name, and separating the function name from its argument list would have reduced readability. That left the slightly unusual position between the return type and the function name as the best of a bad bunch.
The rest is history. Later compilers took advantage of the nascent __attribute__ syntax to put the calling convention keyword in a more appropriate place, but DOS-based compilers (of which Microsoft C was one of the first) shoved it after the return type.
Both the __stdcall and the position of the keyword are Microsoft specific. Any compiler vendor is able to add non-standard syntax to their implementation.
At the very top of this MSDN article:
Microsoft Specific
It also mentions the WINAPI macro at the end of the page:
In the following example, use of __stdcall results in all WINAPI function types being handled as a standard call: [...]`
This form works on both Microsoft C++ Compiler and the MinGW toolchain, which implements GCC for Windows.
But in general GCC uses this other form using it's attributes:
int WinMain() __attribute__((stdcall)) // or WINAPI if using the macro
{}
It's possible however that in the future we have those in a more standard syntax (the stdcall part still being platform specific) by using the recent C++11 generalized attributes such as.
[[ms::stdcall]]
int WinMain() {}
In fact both GCC and Clang already supports the standard generalized attributes as an alternative to the compiler specific attribute syntax.
The answer to your clear question:
WINAPI, Is it a standard C?
is No. __stdcall is a Microsoft extension.
WINAPI is a macro defined in windows.h, which expands to __stdcall. Both windows.h and __stdcall are Windows-specific -- no industry-wide standard defines any aspect of their meaning.
The C and C++ standards do define keywords that have related effects on a function definition: inline, _Noreturn (C2011), and static. All of these keywords are normally placed before the return type, but if I'm reading C2011 correctly, this is not actually required by the syntax: you could perfectly well write
int static foo(void) { return 42; }
These keywords are called function specifiers and storage class specifiers.
Do not confuse them with type specifiers and type qualifiers, which can also appear in this position, but modify the return type when they do.

C vs C++ function questions

I am learning C, and after starting out learning C++ as my first compiled language, I decided to "go back to basics" and learn C.
There are two questions that I have concerning the ways each language deals with functions.
Firstly, why does C "not care" about the scope that functions are defined in, whereas C++ does?
For example,
int main()
{
donothing();
return 0;
}
void donothing() { }
the above will not compile in a C++ compiler, whereas it will compile in a C compiler. Why is this? Isn't C++ mostly just an extension on C, and should be mostly "backward compatible"?
Secondly, the book that I found (Link to pdf) does not seem to state a return type for the main function. I check around and found other books and websites and these also commonly do not specify return types for the main function. If I try to compile a program that does not specify a return type for main, it compiles fine (although with some warnings) in a C compiler, but it doesn't compile in a C++ compiler. Again, why is that? Is it better style to always specify the return type as an integer rather than leaving it out?
Thanks for any help, and just as a side note, if anyone can suggest a better book that I should buy that would be great!
Firstly, why does C "not care" about the scope that functions are defined in, whereas C++ does?
Actually, C does care. It’s just that C89 allows implicitly declared functions and infers its return type as int and its parameters from usage. C99 no longer allows this.
So in your example it’s as if you had declared a prototype as
int dosomething();
The same goes for implicit return types: missing return types are inferred as int in C89 but not C99. Compiling your code with gcc -std=c99 -pedantic-errors yields something similar to the following:
main.c: In function 'main':
main.c:2:5: error: implicit declaration of function 'donothing' [-Wimplicit-function-declaration]
main.c: At top level:
main.c:5:6: error: conflicting types for 'donothing'
main.c:2:5: note: previous implicit declaration of 'donothing' was her
For the record, here’s the code I’ve used:
int main() {
donothing();
return 0;
}
void donothing() { }
It's because C++ supports optional parameters. When C++ sees donothing(); it can't tell if donothing is:
void donothing(void);
or
void donothing(int j = 0);
It has to pass different parameters in these two cases. It's also because C++ is more strongly typed than C.
int main() {
donothing();
return 0;
}
void donothing() { }
Nice minimum working example.
With gcc 4.2.1, the above code gets a warning regarding the conflicting types for void donothing() with default compiler settings. That's what the C89 standard says to do with this kind of problem. With clang, the above code fails on void donothing(). The C99 standard is a bit stricter.
It's a good idea to compile your C++ code with warnings enabled and set to a high threshold. This becomes even more important in C. Compile with warnings enabled and treat implicit function declarations as an error.
Another difference between C and C++: In C++ there is no difference between the declarations void donothing(void); and void donothing(); There is a huge difference between these two in C. The first is a function that takes no parameters. The latter is a function with an unspecified calling sequence.
Never use donothing() to specify a function that takes no arguments. The compiler has no choice but to accept donothing(1,2,3) with this form. It knows to reject donothing(1,2,3) when the function is declared as void donothing(void).
he above will not compile in a C++ compiler, whereas it will compile in a C compiler. Why is this?
Because C++ requires a declaration (or definition) of the function to be in scope at the point of the call.
Isn't C++ mostly just an extension on C
Not exactly. It was originally based on a set of C extensions, and it refers to the C standard (with a few modifications) for the definitions of the contents of standard headers from C. The C++ "language itself" is similar to C but is not an extension of it.
and should be mostly "backward compatible"?
Emphasis on "mostly". Most C features are available in C++, and a lot of the ones removed were to make C++ a more strictly typed language than C. But there's no particular expectation that C code will compile as C++. Even when it does, it doesn't always have the same meaning.
I check around and found other books and websites and these also commonly do not specify return types for the main function
The C and C++ standards have always said that main returns int.
In C89, if you omit the return type of a function it is assumed to be int. C++ and C99 both lack this implicit int return type, but a lot of C tutorial books and tutorials (and compilers and code) still use the C89 standard.
C has some allowances for implementations to accept other return types, but not for portable programs to demand them. Both languages have a concept of a "freestanding implementation", which can define program entry and exit any way it likes -- again, because this is specific to an implementation it's not suitable for general teaching of C.
IMO, even if you're going to use a C89 compiler it's worth writing your code to also be valid C99 (especially if you have a C99 compiler available to check it). The features removed in C99 were considered harmful in some way. It's not worth even trying to write code that's both C and C++, except in header files intended for inter-operation between the languages.
I decided to "go back to basics" and learn C.
You shouldn't think of C as a prerequisite or "basic form" of C++, because it isn't. It is a simpler language, though, with fewer features for higher-level programming. This is often cited as an advantage of C by users of C. And an advantage of C++ by users of C++. Sometimes those users are the same people using the languages for different purposes.
Typical coding style in C is different from typical coding style in C++, and so you might well learn certain basics more readily in C than in C++. It is possible to learn low-level programming using C++, and the code you write when you do so may or may not end up looking a lot like C code.
So, what you learn while learning C may or may not inform the way you write C++. If it does, that may or may not be for the better.
C++ has changed these rules on purpose, to make C++ a more typesafe language.
C.1.4 Clause 5: expressions [diff.expr]
5.2.2
Change: Implicit declaration of functions is not allowed
Rationale: The type-safe nature of C++.
Effect on original feature: Deletion of semantically well-defined feature. Note: the original feature was
labeled as “obsolescent” in ISO C.
Difficulty of converting: Syntactic transformation. Facilities for producing explicit function declarations
are fairly widespread commercially.
How widely used: Common.
You can find other similar changes in appendix C of this Draft C++ standard
Isn't C++ mostly just an extension on C
No. If you think of C++ as "C with Classes", you're doing it very, very wrong. Whilst strictly, most valid C is valid C++, there's virtually no good C that's good C++. The reality is that good C++ code is vastly different to what you'd see as good C code.
Firstly, why does C "not care" about the scope that functions are
defined in, whereas C++ does?
Essentially, because not enforcing the same rules as C++ makes doing this in C hideously unsafe and in fact, nobody sane should ever do that. C99 tightened this up, along with implicit-int and other defects in the C language.

Using void in functions without parameter?

In C++ using void in a function with no parameter, for example:
class WinMessage
{
public:
BOOL Translate(void);
};
is redundant, you might as well just write Translate();.
I, myself generally include it since it's a bit helpful when code-completion supporting IDEs display a void, since it ensures me that the function takes definitely no parameter.
My question is, Is adding void to parameter-less functions a good practice? Should it be encouraged in modern code?
In C++
void f(void);
is identical to:
void f();
The fact that the first style can still be legally written can be attributed to C.
n3290 § C.1.7 (C++ and ISO C compatibility) states:
Change: In C++, a function declared with an empty parameter list takes
no arguments.
In C, an empty parameter list means that the number and
type of the function arguments are unknown.
Example:
int f(); // means int f(void) in C++
// int f( unknown ) in C
In C, it makes sense to avoid that undesirable "unknown" meaning. In C++, it's superfluous.
Short answer: in C++ it's a hangover from too much C programming. That puts it in the "don't do it unless you really have to" bracket for C++ in my view.
I see absolutely no reason for this. IDEs will just complete the function call with an empty argument list, and 4 characters less.
Personally I believe this is making the already verbose C++ even more verbose. There's no version of the language I'm aware of that requires the use of void here.
I think it will only help in backward compatibility with older C code, otherwise it is redundant.
I feel like no. Reasons:
A lot more code out there has the BOOL Translate() form, so others reading your code will be more comfortable and productive with it.
Having less on the screen (especially something redundant like this) means less thinking for somebody reading your code.
Sometimes people, who didn't program in C in 1988, ask "What does foo(void) mean?"
Just as a side note. Another reason for not including the void is that software, like starUML, that can read code and generate class diagrams, read the void as a parameter. Even though this may be a flaw in the UML generating software, it is still annoying to have to go back and remove the "void"s if you want to have clean diagrams

calling qsort with a pointer to a c++ function

I have found a book that states that if you want to use a function from the C standard library which takes a function pointer as an argument (for example qsort), the function of which you want to pass the function pointer needs to be a C function and therefore declared as extern "C".
e.g.
extern "C" {
int foo(void const* a, void const* b) {...}
}
...
qsort(some_array, some_num, some_size, &foo);
I would not be surprised if this is just wrong information, however - I'm not sure, so: is this correct?
A lot depends on whether you're interested in a practical answer for the compiler you're using right now, or whether you care about a theoretical answer that covers all possible conforming implementations of C++. In theory it's necessary. In reality, you can usually get by without it.
The real question is whether your compiler uses a different calling convention for calling a global C++ function than when calling a C function. Most compilers use the same calling convention either way, so the call will work without the extern "C" declaration.
The standard doesn't guarantee that though, so in theory there could be a compiler that used different calling conventions for the two. At least offhand, I don't know of a compiler like that, but given the number of compilers around, it wouldn't surprise me terribly if there was one that I don't know about.
OTOH, it does raise another question: if you're using C++, why are you using qsort at all? In C++, std::sort is almost always preferable -- easier to use and usually faster as well.
This is incorrect information.
extern C is needed when you need to link a C++ library into a C binary; it allows the C linker to find the function names. This is not an issue with function pointers (as the function is not referenced by name in the C code).