Example

18.03.2009
18:37
Comments Off on Example

The following C code shows the use of callbacks for the specific case of searching for an item in an array (in this case, the first integer is greater than 5). First, the model iteration:
int i

for (i 0 i (
if (basis i > 5)
(
break
)
)

if (i (
printf ( “Item d n”, i)
)
else
(
printf ( “Not Found n”)
)
Next, we see the implementation as a callback:
/ CODE OF THE LIBRARY /
atravesCon int (int arrangement , size t cells
int ( callback) (int index, int item, void parameter)
void parameter)
(
codigoSalida int 0
for (int i 0 i codigoSalida callback (i, meaning i , argument)
if (codigoSalida! 0) (
break
)
)
codigoSalida return
)

/ Application code /
int find (int index, int item, void parameter)
(
if (item> 5) (
(int ) parameter index
return 1
Else ()
return 0
)
)

/ (In another function) /
int index
int found
found atravesCon (array, cells andbuscar, andindice)
if (found) (
printf ( “Item d n”, index)
Else ()
printf ( “Not Found n”)
)
AtravesCon receives notice that an extra parameter to the callback can use for their own purposes. Normally one uses callback parameters such as pointers to application data on the outside of their scope, in this case is the variable that receives the index. This feature is needed only for static field in a language such as C or C (in C and other OO languages other solutions are possible.

Related Products
Understanding SQL and Java Together : A Guide to SQLJ, JDBC, and Related Technologies (The Morgan Kaufmann Series in Data Management Systems) by Jim Melton and Andrew Eisenberg (Paperback – May 2000) Java XML and Web Services Bible by Mike Jasnowski (Paperback – Jan 11, 2002) Definitive Guide to Swing for Java 2, Second Edition by John Zukowski (Paperback – Jan 15, 2000)

Comments are closed.