Table of Contents
Pass Cursor to C ++ Function: Pass Cursor to Function in C ++ is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
C ++ allows you to pass a pointer to a function. To do this, you simply need to declare the function parameter as in a pointer type.
In the simple example below, we pass an unsigned long pointer to a function and change the value inside the function, which reflects back while calling the function:
#include #include using namespace std ; void laySoGiay ( unsigned long * par ); int main () { unsigned long sogiay ; laySoGiay ( & sogiay ); // in gia tri cout << "So giay la: " << sogiay << endl ; return 0 ; } void laySoGiay ( unsigned long * par ) { // Lay so giay hien tai * par = time ( NULL ); return ; }
Running the above C ++ program will produce the following results:
The function, which can accept a pointer, can accept an array as follows:
#include using namespace std ; // khai bao ham: double giaTriTB ( int * arr , int size ); int main () { // mot mang so nguyen co 5 phan tu. int doanhSoBH [ 5 ] = { 122 , 35 , 27 , 235 , 60 }; double trungbinh ; // truyen con tro toi mang duoi dang mot tham so. trungbinh = giaTriTB ( doanhSoBH , 5 ) ; // hien thi ket qua cout << "Gia tri trung binh la: " << trungbinh << endl ; return 0 ; } double giaTriTB ( int * arr , int size ) { int i , sum = 0 ; double trungbinh ; for ( i = 0 ; i < size ; ++ i ) { sum += arr [ i ]; } trungbinh = double ( sum ) / size ; return trungbinh ; }
Frequently Asked Questions
What is Pass Cursor to C ++ Function: Pass Cursor to Function in C ++?
C ++ allows you to pass a pointer to a function.
Why is Pass Cursor to C ++ Function: Pass Cursor to Function in C ++ important?
A clear understanding of Pass Cursor to C ++ Function: Pass Cursor to Function in C ++ helps you make informed decisions, avoid common mistakes, and use the relevant tools or techniques more effectively.
How should beginners approach Pass Cursor to C ++ Function: Pass Cursor to Function in C ++?
Start with the fundamental concepts, follow the examples step by step, and test each change in a safe environment before applying it to important systems or data.
Was this article helpful?
Your feedback helps us improve.
Reader Comments 0
Sign in with email or Google to join the discussion.