function inside a function
function1()
开发者_C百科 {
statement1;
statement2;
function2()
{
statement3;
statement3;
}
}
why does control not enter function2, even though return type of both the functions are same
If you want to enter function2 you have to call it. The fact that you put it inside another function doesn't mean it's going to be executed, but yet declared and defined. You have to explicitly call it
function1()
{
statement1;
statement2;
function2()
{
statement3;
statement3;
}
function2();
}
And indeed Std C doesn't allow this. But it still depends on your compiler, so if you're doing this on some purpose, check with your compiler otherwise just pull the function2 declaration out of the function1's block
This is not legal C as defined by the standard. Does it even compile?
Update: Assuming GCC, CoolStraw's answer is correct.
The answer to the original question is as CoolStraw said that it isn't enough to define a nested function, you have to explicitly call it at the point you want it executed. It must be decalred before that. It has nothing to do with whether it has the same type as the containing function.
As Mat said, defining a function inside a function is not allowed by the C standard. It is a gcc extension also supported by IBM's XLC compiler.
The result type of a function has defaulted to int since the original K&R C circa 1970, and is part of all C standards so far. This is not pseudocode or a gcc extra. It's generally discouraged now because it hides mistakes; for example, if you forget "#include " and use a string function returning a pointer, it will default to returning an int. If those types are the same size, you'll get away with it, but in 64 bit mode with 32 bit ints, discarding the upper half of a pointer and replacing it with the sign extension of the lower half is a nasty bug.
Many compilers can give some kind of message warning that you've omitted the type of a function, and many will also warn that you're calling a non-void function without using the result. Both are legal, both may be exactly what you intended, but both may be errors. And most compilers can also warn about non-standard compliant extensions like gcc's nested functions. If you care about portability, enable warnings like those.
精彩评论