can any one tell me can we declare a function in user defined function ? such as
int sum(int x, int y)
{
int fun( float x);
}
Can we define a function inside a function ? As I know we can't define a function inside a function.
But I just did this and its work fine the code is given below :
{
int main()
{
func1();
return 0;
}
func1()
{
int i = 0;
auto func2()
{
i = 10;
printf("Heloo i am func 2\n");
}
printf("Heloo i am func 1\n");
func2();
}
}
It works very fine .
Now can anyone tell me what is going around how a function inside a function is defined or working properly ?
Can anybody explain to me why the code is working ?
Now when I changed few lines of code it give me following problems
The changes are following:
code:
{
func1()
{
func2();
int i = 0;
auto func2()
{
i = 10;
printf("Heloo i am func 2\n");
}
printf("Heloo i am func 1\n");
}
error:
error: static declaration of ‘func2’ follows non-static declaration
note: previous implicit declaration of ‘func2’ was here
Now what are these error and why are they coming ?
If I call func2() in main function than it will show an error like
undefined reference to func2
Now can anyone tell me what is wrong here ?
The C standard allows the declaration of functions within functions (as in your first code snippet), but not the definition of functions within functions (although some compilers may offer it as a non-standard extension).
The same is true for C++, although newer versions (C++0x, etc.) allow you to define anonymous lambda functions. But this is something different.
gcc allows this in C only (not C++) via -fnested-functions, but this is of course non-standard and non-portable so you should probably not use nested functions unless you have a very good reason.
This, for foo,
int main(void) {
int foo(void);
}
is not a definition of foo. It is a declaration and it is perfectly valid (though strange: function declarations belong outside any other functions) in C.
What C does not allow, which is what you found out, is that definitions cannot be nested.
/* INAVLID EXAMPLE */
int main(void) {
int foo(void) { return 0; }
}
When you call func2() before declaration, C assumes (according to standard) implicit declaration int func2(...), but when compiler finds func2() definition, it differs from previous implicit declaration, so compiler complains about it.
If func2() precedes the call to func2(), it acts as both definition and declaration, so no problem there.
And of course func2() cannot be called from main() as its scope is limited to func1(), like you cannot access local variable from another function.
As others mentioned, nested functions aren't standard in C, although some compilers (like GCC) support this feature.
This is just a supplement to Paul R's answer.
Assuming that your compiler is GCC,
the end of the
document
in Paul's answer says:
A nested function always has no
linkage. Declaring one with extern
or static is erroneous. If you need
to declare the nested function before
its definition, use auto
So func2 has to be declared as auto before the call of it.
If you change the second code
func1()
{
func2();
int i = 0;
...
to
func1()
{
auto func2(); /* declaration added */
func2();
int i = 0;
...
the code will be compiled.
Related
It comes across as odd to me that local function definitions are illegal. As things stand now, I doubt it would be too hard to implement, and the erasure of what could be a potential feature (like in python for example) for no reason at all seems strange, especially for a language like C++, where you can shoot yourself in the foot if you want to. The illegality of local function definitions seems doubly so strange if things like this are allowed.
int main()
{
void func(); // Allowed?
class BypassRules {
public:
static void func() { return; }
};
BypassRules::func();
func();
return 0;
}
void func() { return; }
Oddly enough, local function 'Declarations' are allowed, but definitions are not. And the rule on local function definitions not being allowed can be easily bypassed by writing a class encapsulator. So, could I have some clarification? Why are local class definitions classified as 'illegal' in C++?
Oddly enough, local function 'Declarations' are allowed, but definitions are not. And the rule on local function definitions not being allowed can be easily bypassed by writing a class encapsulator. So, could I have some clarification? Why are local class definitions classified as 'illegal' in C++?
Illegal because they don't make much sense, whether it may be defining a function inside a function or a class inside a function like main().
But then you can always use workarounds, such as:
For functions you can always use a lambda, which acts as an anonymous temporary function, can be called inside main plus be used within function parameters as well.
It can be invoked whenever necessary and subsequently discarded like a throw-away function, but it does the job - whatever you would expect from a function.
Example:
int main()
{
// Define within the scope of main()
auto temp = [](int x)
{ std::cout<< x;
}
temp(10); // call like a function
}
For classes, use static functions, (being local to the translation unit) with public access specifiers (as you did in your question).
Example:
int main()
{
class temp
{ public:
static void a()
{ std::cout<< 10;
}
};
temp::a();
}
Output for both cases: 10
Provided there are alternatives approaches like the ones above to define a function/class/struct inside main(), there isn't really much of a point to make them legal. ¯\_(ツ)_/¯
The following code segment compiles with no problems, even though foo is defined inline but not declared as such, and bar is declared inline but not defined as such.
int foo();
inline int foo() { return 3; }
inline int bar();
int bar() { return 4; }
inline int foobar();
inline int foobar() { return 5; }
int main(){
// ...
}
My first question: does the compiler read foo as inline or not? What about bar? Is this specified by the C++ standard?
My second question: Which one of these is the best practice in declaring and defining inline functions? Is it foo? bar? or foobar? Why?
inb4 I read some other posts related to this but none of them answer my question directly.
This answer seems to suggest that foo is inline, but says nothing about bar. It also doesn't explain why foo is preferred over the others. This answer talks about when I should use inline functions. That's not my concern: I've already decided to use inline functions. My question (question 2, to be precise) is whether I should declare it as such, define it as such, or both, and why one of the conventions is better style than the rest. This question seems to be closer to my concern but nobody answered it.
True for member functions, and not explicitly-defined for non-member functions (I believe)
See §10.1.6 in ISO C++ std.
The inline specifier can be applied only to the declaration or
definition of a variable or function
and
A function declaration (11.3.5, 12.2.1, 14.3) with an inline specifier declares an inline function.
It doesn't explictly state what will happen if an inline specifier only modifies the definition of a function.
What we can be sure of is that such member functions are guaranteed to be marked as inline (thanks to James Curran).
See §12.2.1.
An inline member function (whether static or non-static) may also be
defined outside of its class definition provided either its
declaration in the class definition or its definition outside of the
class definition declares the function as inline or constexpr.
All three functions in GCC and non-member circumstance
As in GCC -O1 C++ mode, every function mentioned are inlined.
Code:
#include "stdio.h"
int foo();
inline int foo() {int i; for(i=0;i<100000;i++); return i+3; }
inline int bar();
int bar() {int i; for(i=0;i<100000;i++); return i+4; }
inline int foobar();
inline int foobar() {int i; for(i=0;i<100000;i++); return i+5; }
int foobar2();
int foobar2() {int i; for(i=0;i<100000;i++); return i+6; }
int main(){
int a,b,c,d;
a=foo();
b=bar();
c=foobar();
d=foobar2();
printf("%d %d %d %d", a, b, c, d);
}
Disassembly:
We can see only foobar2 is called.
As in -O2 and -O3, inline doesn't matter so much. The compiler will decide by itself (in the case above, all 4 functions are inlined).
(NOTE: I reopened this question, as this is NOT a duplicate of the cited older question. That question involved design; this is about syntax).
Now, referring to the question cited by the OP in his question about inline in definition and declaration, the answer states that if the declaration is in a header file, then it was have the "inline" ("bar style"), because other source files using that header will try to link to it as if it were a non-inlined function and file.
Personally, I'd use
inline int foobar() { return 5; }
in the header file without a separate declaration. (I always feel that if it's too big to be in the header, then it's too big to be inlined.)
to declare a function prototype we declare it outside and on the top which means right before the function definition.
1- I wonder why c++ allows declaring prototypes scoped inside the body of other functions' definitions?
2- How to call a function whose prototype being inside another function's body?
here is an example:
#include "stdafx.h"
#include <iostream>
using namespace std;
void Bar()
{
cout << "Bar..." << endl;
void Baz();
}
int main()
{
void Foo();
Foo();
Bar();
Baz(); // how to call this function?
cin.get();
return 0;
}
void Foo()
{
cout << "Foo..." << endl;
}
void Baz()
{
cout << "Baz..." << endl;
}
A function prototype inside one function isn't visible inside another, so the code you've written here won't work. However, there's nothing stopping you from providing another function prototype inside of main:
int main()
{
void Foo();
Foo();
Bar();
void Baz();
Baz();
cin.get();
return 0;
}
That having been said, it's pretty unusual to write code like this - if you mean to prototype the function, just do so at global scope. It's rare to see function prototypes defined inside of individual functions and is almost always a mistake or extremely poor coding style.
C++ allows this for two reasons:
Backwards compatibility. This is legal C code, and historically C++ tried to maintain compatibility with C whenever possible. (There's a lot of legal C code that won't compile in C++, so this isn't a hard-and-fast rule, but it's a good guiding philosophy.)
The "Why Not?" principle. Function prototypes are really just declarations of functions. C++ lets you declare all sorts of objects at different points in time. Allowing function declarations like this inside of a function follows as a special case of allowing for declarations, so explicitly disallowing it would require extra verbage in the spec and potentially might hurt someone in a really bizarre case down the line.
Arguably, this was a bad decision, because it leads to C++'s Most Vexing Parse. The following line of code, for example, is interpreted as a function prototype:
std::vector<int> x(); // Oops - it's a function prototype!
Even worse is something like this:
std::istream input;
std::vector<int> x(istream_iterator<int>(input), istream_iterator<int>()); // Oops - it's a function prototype!
This was addressed by adding in the new brace initialization syntax:
std::vector<int> x{}; // Okay, a vector.
std::vector<int> x{istream_iterator<int>{input}, istream_iterator<int>{}}; // Sure, that's fine too.
Another newbie question:
int foo(); // outer foo function
int main() {
int foo(); // inner foo function
cout << foo() << endl;
}
int foo() { // one definition
return 42;
}
From my understanding, an inner declaration of either function or object will hide outer one, if any.
So the above outer foo() and inner foo() should be two distinct functions.
But they are sharing one definition, which seems confusing.
Is it legal that two distinct functions share one definition? How about two distinct object variables?
(This is C++ question but the syntax seems also fits C.)
Edit:
It is verified that outer and inner foo are the same funciton using pointer to function:
pf_outer = 0x400792
pf_inner = 0x400792
The inner foo is just another forward deceleration of the same foo(). Consider the following example:
int foo();
int foo();
int main() {
cout << foo() << endl;
}
int foo() { // one definition
return 42;
}
This will compile and run and there is no ambiguity because the compiler will replace the use of the same function with the same code.
It is fine to re declare functions.
This is perfectly fine to redeclare a function like this, we can see this from draft C++ standard in two places, in section 3.1 Declarations and definitions which says:
A declaration (Clause 7) may introduce one or more names into a
translation unit or redeclare names introduced by previous
declarations.[...]
and goes on to say:
A declaration is a definition unless it declares a function without
specifying the function’s body [...]
and in section 13.1 Overloadable declarations paragraph 3 which says:
Parameter declarations that differ only in the use of equivalent
typedef “types” are equivalent. A typedef is not a separate type, but
only a synonym for another type (7.1.3). [ Example:
typedef int Int;
void f(int i);
void f(Int i); // OK: redeclaration of f(int)
void f(int i) { /* ... */ }
void f(Int i) { /* ... */ } // error: redefinition of f(int)
—end example ]
Both declarations will refer to the same definition, you are not allowed to redefine the function.
The function declarations of are also allowed to differ by their outermost cv-qualifiers as well.
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
...
}