Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does c++ allow function call outside any funtion?

Tags:

c++

linux

I have code

#include <stdlib.h>

void *gg = malloc(55);

int main(int argc, char **argv)
{
        return 0;
}

gcc fail to compile but g++ works.

So, I just want to make sure that the malloc calling happens before main is exectued.

like image 202
Mr Pang Avatar asked Mar 15 '19 07:03

Mr Pang


People also ask

Can we call function outside a function?

Simple answer: you cannot.

Can C functions call other functions?

The main function always acts as a driver function and calls other functions. We can also write function call as a parameter to function.

Can you call a function outside of main in C?

The function which is declared outside the main( ), which is a global declaration, can be accessed by any function outside and inside the main() function.

Can C functions call themselves?

In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. The C programming language supports recursion, i.e., a function to call itself.


1 Answers

What you do is allowed in C++. The C++ standard has a whole section on "Dynamic initialization of non-local variables".

Looking at the assembly generated by GCC for your code is instructive:

Here the initializers are called through two generated functions, _GLOBAL__sub_I_gg (which is called before main) which in turn calls __static_initialization_and_destruction_0.

It is within the body of the latter function you will find the call to malloc.

like image 165
P.W Avatar answered Oct 16 '22 09:10

P.W