Skip to content

Instantly share code, notes, and snippets.

@mu-777
Created June 18, 2015 09:44
Show Gist options
  • Save mu-777/a6ecfd71f27a190b991d to your computer and use it in GitHub Desktop.
Save mu-777/a6ecfd71f27a190b991d to your computer and use it in GitHub Desktop.
swaps.cpp
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string.h>
// プロトタイプ宣言
void swap1(int x, int y);
void swap2(int* x, int* y);
void swap3(int& x, int& y);
void main() {
// int型の宣言・初期化
int a = 10;
int b = 20;
// フォーマット指定子でコンソール出力
// &aと&bは16進数.差がどうなっているかを確認.なぜそうなってるのか理解する.
printf("初期値:a=%d, b=%d, &a=%#-8x, &b=%#-8x¥n¥n", a, b, &a, &b);
//--------------------------------------
printf("--swap1(int x, int y)←(a, b)-------------------------¥n");
swap1(a, b);
printf("a=%d, b=%d, &a=%#-8x, &b=%#-8x¥n¥n", a, b, &a, &b);
//スワップしてない!
//--------ポインタ引数------------------------------------
a = 10;
b = 20;
printf("--swap2(int* x, int* y)←(&a, &b)-----------------------¥n");
swap2(&a, &b);
printf("a=%d, b=%d, &a=%#-8x, &b=%#-8x¥n¥n", a, b, &a, &b);
//--------------------------------------
//--------参照引数------------------------------
a = 10;
b = 20;
printf("--swap3(int &x, int &y)←(a, b)-------------------------¥n");
swap3(a, b);
printf("a=%d, b=%d, &a=%#-8x, &b=%#-8x¥n¥n", a, b, &a, &b);
//--------------------------------------
}
void swap1(int x, int y) {
int temp;
temp = y;
y = x;
x = temp;
printf("x=%d, y=%d, &x=%#-8x, &y=%#-8x¥n", x, y, &x, &y);
printf(" &xは仮引数のアドレスの番地,xは仮引数のアドレスの中身を表す.¥n");
printf(" 関数内ではxとyの値は入れ替わっている¥n");
}
void swap2(int* x, int* y) {
int temp;
temp = *y;
*y = *x;
*x = temp;
printf("x=%d, y=%d, &x=%#-8x, &y=%#-8x¥n", x, y, &x, &y);
printf(" &xは実引数のアドレスの番地を入れた仮引数のアドレスの番地,¥n");
printf(" *xはxというアドレス(実引数のアドレス)の中身,¥n");
printf(" xは実引数のアドレスの番地が入った仮引数のアドレスの中身を表す.¥n");
printf(" 関数内ではxとyの値は入れ替わっている¥n");
}
void swap3(int& x, int& y) {
int temp;
temp = y;
y = x;
x = temp;
printf("x=%d, y=%d, &x=%#-8x, &y=%#-8x¥n", x, y, &x, &y);
printf(" &xは実引数のアドレスの番地,xは実引数のアドレスの中身を表す.¥n");
printf(" 関数内ではxとyの値は入れ替わっている¥n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment