[C con Clase] Duda
Steven Davidson
srd4121 en njit.edu
Vie Dic 9 15:16:50 CET 2011
Hola Óscar,
2011/12/9 Oscar AH <enigma-si en hotmail.com>:
> Hola que tal como estais.
>
> Tengo el siguiente código :
>
> #include <iostream>
>
> void swap(int *x, int *y);
>
> int main()
> {
> int x = 5, y = 10;
>
> std::cout << "Main. Before swap, x: " << x
> << " y: " << y << "\n";
> swap(&x, &y);
> std::cout << "Main. After swap, x: " << x
> << " y: " << y << "\n";
> return 0;
> }
>
> void swap(int *px, int *py)
> {
> int temp;
>
> std::cout << "Swap. Before swap, *px: " << *px
> << " *py: " << *py << "\n";
>
> temp = *px;
> *px = *py;
> *py = temp;
>
> std::cout << "Swap. After swap, *px: " << *px
> << " *py: " << *py << "\n";
> }
>
> que produce la siguiente salida :
>
> Main. Before swap, x: 5 y: 10
> Swap. Before swap, *px: 5 *py: 10
> Swap. After swap, *px: 10 *py: 5
> Main. After swap, x: 10 y: 5
>
> No entiendo por qué si en main después del primer Main. Before swap salta a
> Swap. Before swap.
>
> ¿Me lo podeis explicar por favor?
>
Porque en 'main()', se invoca a 'swap()', por lo tanto se ejecuta sus
sentencias; esto es,
1) int x = 5, y = 10;
2) std::cout << "Main. Before swap, x: " << x
<< " y: " << y << "\n";
3) swap(&x, &y);
Dentro de 'swap()':
3.1) int temp;
3.2) std::cout << "Swap. Before swap, *px: " << *px
<< " *py: " << *py << "\n";
Espero haberte orientado un poco.
Steven
Más información sobre la lista de distribución Cconclase