2019年12月11日 星期三

C語言 全域變數 局部變數 傳值 傳址

#include <stdio.h>
//全域變數
int a, b;
int *p1, *p2 ;

void swap(int a ,int b)
{
  int temp1=0;//局部變數
  temp1 = a;
  a = b;
  b = temp1;
  printf("Values of a and b is %d  %d\n",a,b);

}

void swap1(int x ,int y)
{
  int temp1=0;//局部變數
  temp1 = x;
  x = y;
  y = temp1;
  printf("Values of x and y is %d  %d\n",x,y);
  a = x;
  b = y;
}

void swap2(int *p1 ,int *p2)
{
    int temp2=0;//局部變數
    temp2 = *p1;
    *p1 = *p2;
    *p2 = temp2;
}

void main()
{
    a=3;
    b=5;
    printf("a的值:%d\n", a);
    printf("b的值:%d\n", b); 
 
    swap(a,b);
    //傳值 call by value
    printf("\n1. 傳值 call by value\n");
    printf("a的值:%d\n", a);
    printf("b的值:%d\n", b);
 
    swap1(a,b);
    //傳值 call by value
    printf("\n2. 傳值 call by value\n");
    printf("a的值:%d\n", a);
    printf("b的值:%d\n", b);
     
    //傳址 call by reference
    p1 = &a;
    p2 = &b;
    swap2(p1,p2);
    printf("\n3. 傳址 call by reference\n");
    printf("*p1的值 :%d\n", *p1);
    printf("*p2的值:%d\n", *p2);
 
}


a的值: 3                                                                   
b的值:5                                                                                  
Values of a and b is 5  3                                                                     
1. 傳值 call by value                                                       
a的值:3                                                                   
b的值:5                                                                      

                        
Values of x and y is 5  3                                                 
2. 傳值 call by value                                                       
a的值:5                                                                   
b的值:3  

3. 傳址 call by reference                                                   
*p1的值 :3                                                                 
*p2的值: 5   


沒有留言:

張貼留言

Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3

  Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3 AngularJS 實例 <!DOCTYPE html> <html> <head> <meta charse...