C++ void prefixed to a function call. eg. `main() {void func();}` - c++

void func() {assert(0);}
int main () {void func();}
The above code does not call func(), or at least does not reach the assertion. Not that I really need to know, but I'm just curious, what is going on here?

You're declaring a prototype for a function named func which returns nothing and takes no arguments. That's (one of) the subtle difference between function calls and function prototypes. Notice that the line above main, the void func() {assert(0);}, has no effect on whether this is a prototype or a call. You could remove it and the code would do the same thing - that is, nothing.
This also tells you that you can redeclare function prototypes. You could even have this:
int main() {
void blah();
void blah();
void blah();
void blah();
}
And the code would still do what it did before - nothing.
If you leave off the void, it would call the function.
Also, notice that in the case of a function which takes parameters, this:
int main() { func(4); }
would not turn into a prototype if you added void before it like this:
int main() { void func(4); }
it would just produce a syntax error.

As others have pointed out, the line
void func();
inside of main is treated as a function prototype rather than a call to the function func. In C and C++, you can declare function prototypes inside of functions if you wish, though it's rarely done in practice.
The fact that this is legal causes all sorts of headaches for programmers. For example, if you rewrote the code as
(void) func();
Then this would compile as a call to func whose return type is explicitly casted to void to indicate "I don't care about this return value." In other words, this set of parentheses changes the declaration into a statement.
In C++, this problem can be compounded by the fact that this code below is a function prototype, not a variable declaration invoking the default constructor:
Object myObject();
Though
Object myObject(137);
does create the object and pass 137 into its constructor, and
Object myObject;
creates the object without calling the constructor.
There is an awful edge case of the language called the "most vexing parse" that arises when trying to declare an object while calling its constructor. For example, this code is legal C++, but it's a function declaration rather than a variable declaration:
set<int> mySet(istream_iterator<int>(cin), istream_iterator<int>());
The problem is that this could be parsed as a function declaration rather than a creation of an object that accepts two temporary istream_iterator<int>s as parameters. To fix this, in C++ you'd have to write
set<int> mySet(istream_iterator<int>(cin), (istream_iterator<int>()));
Where, as above, the extra parentheses forcibly disambiguate the statement from being a function prototype to being a declaration.
Hope this helps!

You can declare functions, even when it's unnecessary. That's what you've done, re-declared the function.

You are declaring a local function void func() inside main().
The void statement indicates the compiler that it is a declaration and not a function call. So, remove the void, your function will be called.

Related

How to leave a declared function undefined in C++ like with `undefined` in Haskell?

In Haskell there is a constant called undefined that you can use to
declare a function without defining it (i.e. a function prototype with an empty body) as with squarein
square :: Int -> Int -- declaration
square = undefined -- empty definition
main = putStrLn.show.square $ 3
This is tremendously useful to defer the work on square and focus on getting the main function right first, because the Haskell compiler makes sure that the whole file compiles as if square was defined.
The C++ equivalent is
#import <iostream>
int square(int x){
//TODO incomplete
return 0;
}
int main() {
std::cout << square(3);
}
My intention is to invoke a compiler like clang++ as a typechecker for main alone and work on square later. Imagine that square really is one of many not-yet-defined complex functions that return a complex data structure with a non-trivial constructor. I would have to write a lot of code to create returnable objects just to get the functions to compile.
Is there something quick-and-dirty in C++ similar to undefined?
Thank you #molbdnilo.
Using throw is concise and works perfectly:
int square(int x) {
throw("undefined");
}
You can also use assert as following:
int square(int x)
{
assert(0);
}
This has the advantage that it can't be caught and will always fail. This will protect you better in case you forget to implement the function.
C++ has pure virtual functions, for use in abstract base classes.
class foo {
virtual void bar() = 0;
};
The function foo::bar() cannot be called, and indeed a foo object cannot even be created, but it can be overridden in a derived class of foo. You can, however, give a definition for it that derived classes inherit by default.
Another thing in C++ that’s somewhat similar to undefined is an uninitialized function pointer. A safer, more modern solution might be a lambda expression or static stub function that aborts the program.
The meaning of undefined in actual use is something like: a placeholder that will crash the program if you try to actually call it, but which compiles correctly and will be type-checked. For individual object files, declaring an extern prototype for a function that isn’t defined anywhere will do the job. If you’re linking the whole program, there has to be some kind of definition (although function pointers can get around that, at the cost of safety), but it can be a stub.

Function Prototype/Definition

If we do not mention the function prototype,call the function from the main and write the definition after main it gives an error.If we write the function definition before main and do not write the prototype the program works fine. So my question is if we write the function definition before main(without writing the prototype) does it solve the problem of not declaring a function prototype(i.e, the compiler will start reading from top-down and will still be able to know about the function name,return type,parameters and etc)
Defining the function with no prior prototype is semantically equivalent to declaring the prototype immediately before defining the function. So yes, it's safe: defining a function without a prototype, before any uses of the function, will work just fine.
Compiler goes at function definition when you make a call to that function. While function prototype is consulted for arguments and return type checking. So, you can safely emit function prototype in your case...
Yes (for C++), compiler will accept this. To call a function compiler must see its prototype or definition before. Also translation units (cpp) files are compiled from top to bottom, so:
void foo();
void foo2() {
}
int main() {
foo();
foo2();
}
void foo() {
}
are both correct. If you would provide foo() prototype without defining foo below main(), compiler will still accept your code, but linker would complain with error.

What happens if compiler inlines a function which is called through a function pointer

Let us say I have a function in my program and somewhere in my code, that function is called through a function pointer. What happens if the compiler happened to inline that function, or would the compiler realize that there is a function pointer assigned to that function and therefore avoid inlining it.
When a pointer to a function is taken, the compiler will generate an out-of-line body for the function. It is still possible to inline the function at other call sites.
Note that a function marked inline must have a definition available in all TUs which refer to it, and these definitions must be identical. Which means it's perfectly safe to inline the function at some call sites and keep it out-of-line at others.
Well, it will surely work. I don't see how inlining would prevent that. You just have some code that calls the function directly, and it might be inlined there, and you have some code which calls it through a function pointer, just as a regular function.
There's no reason that using a function pointer should prevent inlining. Inlining is done on a case-by-case basis and can exist alongside a usual function body. So a function can be inlined in one place, and called in another.
The compiler will, therefore, inline where it can and still produce a callable function for your function pointer.
Not only does the compiler inline "other calls of the function", but it may even inline calls through function pointers if it understands enough about which function is actually being used, something like this:
typedef void (*funcptr)();
void somefunc()
{
... do stuff here ...
}
void indirection(funcptr *f)
{
f();
}
void call_with_ptr()
{
funcptr f = somefunc();
for(int i = 0; i < 100; i++)
{
indirection(f);
}
}
I had code similar to this, and it inlined the indirection, and made the call to somefunc() a direct call without using the function pointer.
But of course, this assumes the compiler can figure out which function is called from the code - which is obvious in this case, but if there is runtime decisions involved, it may not do so.

What does it means if I declare function pointer in c++

What does it means when I in my code declare something like :
Foo * foo();
What benefits it gives me ?
Ist not simple pointer variable as you see .
Also
What does it mean if I declare it in the c++ source above all methods for example :
// Test cpp class
.
#include "Foo.h"
Foo * foo();
Test::Test() {}
Test::GetFooMethods()
{
foo()->someMethod();
}
…
…
Foo * foo(); is a declaration to a function named foo which returns a pointer to a Foo object. It is not a function pointer.
The code Foo()->someMethod(); is probably a typo. You probably meant foo()->someMethod();. In this case, the code calls foo() which as stated above returns a pointer to a Foo object, and then you call the Foo::someMethod() method through that pointer.
If in fact you did mean Foo()->someMethod(); things get a little crazy. What this means is first a Foo object is default initialized on the stack. Then Foo::operator->() is called, returning some object which has a method named someMethod(), and that function is called. See why I guess that it was a typo? :)
EDIT:
To answer the last question in your post, when you declare a function without defining it, you are telling the compiler, "I've got a function named foo that takes no parameters and returns a pointer to a Foo, but I'm not going to tell you how that function is implemented yet." This allows you to write code that uses that function and the compiler will be happy. The linker however will be quite grumpy with you if you do not someplace provide a definition for this function.
Foo * foo();
This is not a function pointer. This is a declaration of a function named foo that takes no arguments and returns a pointer to a Foo.
A pointer to a function of this type would look like:
Foo* (*foo_ptr)() = foo;
Just like
int getX();
is a declaration of a function that returns an int, so too
Foo * foo();
is a declaration of a function that returns a Foo pointer;
What does it means when I in my code
declare something like : Foo * foo();
Foo * foo();
Very tough to say without knowing what is Foo.
If Foo is a type e.g. struct Foo{};, then this declares a function named 'foo' which returns a pointer to some type called Foo. This looks to be the case in your post based on your usage subsequently (and also the title of the post).
If Foo is a #define e.g. #define Foo 1, then this is not a declaration but an expression statement which multiplies 1 by the return value of 'foo' in case operator * is defined for the types of the operands involved.
What benefits it gives me ?
Tough to say again without knowing what Foo is.
Also What does it mean if I declare it
in the c++ source above all methods
Declaring 'foo' (if it is indeed a declaration) as high as possible in the translation unit means larger the tentative scope of the name 'foo'.
void f1(){g();} // not OK, 'g' not known
void f(){}
void g(){f();} // OK, f() is known
BTW, does Foo (caps F) have an overloaded operator ->?

Nested functions are not allowed but why nested function prototypes are allowed? [C++]

I was reading the linked question which leads me to ask this question.
Consider the following code
int main()
{
string SomeString();
}
All says, compiler takes this as a function prototype and not as a string object. Now consider the following code.
int main()
{
string Some()
{
return "";
}
}
Compiler said this is invalid as I guess nested function definition is not allowed. If it is not allowed, why nested function prototypes are allowed? It is not giving any advantage rather than making confusion (or am I missing some valid points here?).
I figured out the following is valid.
int main()
{
string SomeFun();
SomeFun();
return 0;
}
string SomeFun()
{
std::cout << "WOW this is unexpected" << std::endl;
}
This is also confusing. I was expecting the function SomeFun() will have a scope only in main. But I was wrong. Why compiler is allowing to compile code like the above? Is there any real time situations where code like the above makes sense?
Any thoughts?
Your prototype is just 'Forward Declaration'. Please check out the Wikipedia article.
Basically, it tells the compiler "don't be alarmed if the label 'SomeFun' is used in this way". But your linker is what's responsible for finding the correct function body.
You can actually declare a bogus prototype, e.g. 'char SomeFun()' and use it all over your main. You will only get an error when your linker tries to find the body of your bogus function. But your compiler will be cool with it.
There are lots of benefits. You have to remember the function body is not always in the same source code file. It can be in a linked library.Also, that linked library may be have a specific 'link signature'.Use conditional defines you may even select the correct link signature at build time using your scoped prototypes.Although most people would use function pointers for that instead.
Hope this helps.
Just as a side note, C++03 does have a roundabout way of defining local functions. It requires abusing the local-class feature:
int main()
{
struct Local
{
static string Some()
{
return "";
}
};
std::cout << Local::Some() << std::endl;
}
This is a convention from C -- like many -- which C++ has adopted.
The ability to declare a function inside another function in C is a decision that most programmers probably consider regrettable and unnecessary. Particularly with modern OOP design where function definitions are comparatively smaller than they are in C.
If you would like to have functions that only exist in the scope of another function, two options are boost::lambda and C++1x lambda.
As to why your declaration of
void f() {
void g(); g();
}
is better than this one
void g();
void f() {
g();
}
It's generally good if you keep declarations as local as possible, so that as few name clashes as possible result. I say it's arguable whether declaring a function locally (this way) is really fortunate, as i think it's still better to ordinary include its header and then go the "usual" way, which is also less confusing to people not knowing about that. Sometimes, it's also useful to work around a shadowed function
void f() {
int g;
// oops, ::g is shadowed. But we can work around that
{
void g(); g();
}
}
Of course, in C++ we could call function g using its_namespace::g() - but in the old days of C, that wouldn't have been possible, and that thing allowed the programmer to still access the function. Also note that while syntactically it is not the same, semantically the following does also declare a function within a local scope, that actually targets a different scope.
int main() {
using std::exit;
exit();
}
As a side note, there are more situations like that where the target scope of a declaration is not the scope where that declaration appears in. In general, the entity you declare becomes a member of the scope in which the declaration appears. But that's not always the case. Consider for example friend declarations, where that thing happens
struct X { friend void f() { std::cout << "WoW"; } };
int main() { void f(); f(); } // works!
Even though the function declaration (and definition!) of f happened within the scope of X, the entity (the function itself) became a member of the enclosing namespace.
Function prototypes are hints for the compiler. They indicate that the functions are implemented somewhere else, if not already discovered. Nothing more.
When you declare a prototype as you are doing you are basically telling the compiler to wait for the linker to resolve it. Depending where you write the prototype the scoping rules apply. There is nothing technically wrong writing the prototype inside your main() function (although IMHO a bit messier), it just means that the function is only locally known inside the main(). If you would have declared the prototype at the top of your source file (or more commonly in a header file), the prototype/function would be known in the whole source.
string foo()
{
string ret = someString(); // Error
return ret;
}
int main(int argc,char**argv)
{
string someString();
string s = somestring(); // OK
...
}