C语言函数

2019-06-09  本文已影响0人  arkliu

创建并使用简单的函数

#include <stdio.h>
#define LABEL '*'
#define NAME "王五"
#define AGE 35

void printSplit(void);

int main()
{
    printSplit();
    printf("姓名:%s\n", NAME);
    printf("年龄:%d\n", AGE);
    printSplit();
    return 0;
}

void printSplit(void) {
    for (size_t i = 0; i < 10; i++)
    {
        putchar('*');
    }
    putchar('\n');
}
image.png

函数参数

#include <stdio.h>

void printSplit(int);

int main()
{
    for (size_t i = 1; i < 10; i++)
    {
        printSplit(i);
    }
    return 0;
}

void printSplit(int width) {
    for (size_t i = 0; i < width; ++i)
    {
        putchar('*');
    }
    putchar('\n');
}
image.png

使用return从函数中返回值

#include <stdio.h>

int calcMin(int,int);

int main()
{   int first, second;
    printf("请输入两个整数:\n");
    scanf("%d", &first);
    scanf("%d", &second);
    printf("数字%d 和%d 之间的最小数是%d", first, second, calcMin(first, second));
    return 0;
}

int calcMin(int m, int n) {
    int min = m < n ? m : n;
    return min;
}
image.png

查找地址&运算符

#include <stdio.h>

void address(int);

int main()
{
    int first = 30;
    int second = 40;
    printf("first is :%d , &first is :%p\n", first, &first);
    printf("second is :%d , &second is :%p\n", second, &second);
    address(second);
    return 0;
}

void address(int second) {
    int first = 10;
    printf("in address first is :%d , &first is :%p\n", first, &first);
    printf("in address second is :%d , &second is :%p\n", second, &second);
}
image.png

使用指针在函数之间传递数据

#include <stdio.h>

void exchange(int *, int *);

int main()
{
    int first = 30;
    int second = 40;
    printf("original first is :%d , second is :%d\n", first, second);
    exchange(&first, &second);
    printf("after first is :%d , second is :%d\n", first, second);
    return 0;
}

void exchange(int * first, int * second) {
    int temp;
    temp = *first;
    *first = *second;
    *second = temp;
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读