Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Address of a function in C or C++
In C and C++, every function is stored in the computer's memory, and each function has a memory address just like all other variables. In this article, our task is to see how we can access the address of a function and display it in both C and C++.
Accessing Address of a Function
To access the address of a function, we simply use its name without parentheses. When we print a function name with parentheses like hello(), we're calling the function. But if we print just hello, it gives us the memory address where the function is stored.
C++ Program to Display the Address of a Function
Following is a C++ program where we define a function called my_function. We call it inside the main() function and then display the memory addresses of both my_function and the main() function.
#include <iostream>
using namespace std;
// defining a simple function
void my_function() {
cout << "Hello TutorialsPoint Learner!" << endl;
}
int main() {
// calling the function
cout << "Calling my_function: ";
my_function();
// printing the function's address
cout << "The address of my_function is: " << (void*)my_function << endl;
// printing the address of main function
cout << "The address of main() function is: " << (void*)main << endl;
return 0;
}
The output of the above program is shown below. It displays the memory addresses of both the defined function and the main function.
Calling my_function: Hello TutorialsPoint Learner! The address of my_function is: 0x559cc9037189 The address of main() function is: 0x559cc90371bf
C Program to display the Address of a Function
Here's a C program where we do the same as in the C++ example. We first define a function and call it, then display the memory addresses of both my_function and main() function.
#include <stdio.h>
// defining a simple function
void my_function() {
printf("Hello World\n");
}
int main() {
// calling the function
printf("Calling my_function: ");
my_function();
// printing the address of my_function
printf("The address of my_function is: %p\n", (void*)my_function);
// printing the address of main
printf("The address of main is: %p\n", (void*)main);
return 0;
}
Below is the output of the above program, which displays the memory addresses of both the defined function and the main function.
Calling my_function: Hello World The address of my_function is: 0x55e7afc43169 The address of main is: 0x55e7afc43183
Conclusion
To conclude, we saw that every function in C and C++ has a memory address, just like variables. We can access this address by writing the function name without parentheses and display it using a simple program.