c语言中函数、函数式宏

c语言中函数、函数式宏例子

返回一个数的平方。

1、函数

#include <stdio.h>

int sqr_int(int x)
{
    return x * x;    
} 

double sqr_double(double x)
{
    return x * x;
}

int main(void)
{
    int a;
    puts("please input an integer.");
    printf("a = "); scanf("%d", &a);
    printf("int  result: %d\n", sqr_int(a));
    
    double b;
    puts("please input an double.");
    printf("b = "); scanf("%lf", &b);
    printf("double result: %f\n", sqr_double(b));
    
    return 0;
}

 

 

2、函数式宏

#include <stdio.h>

#define sqr(x) ((x) * (x))

int main(void)
{
    int a;
    puts("please input an integer.");
    printf("a = "); scanf("%d", &a);
    printf("int result: %d\n", sqr(a));
    
    double b;
    puts("please input an double");
    printf("b = "); scanf("%lf", &b);
    printf("double result: %f\n", sqr(b));
    
    return 0; 
}

 

 

3、函数和函数式宏的区别

1、函数式宏是在编译时展开并填入程序的

2、函数更为严格,需要指定返回值类型、形参类型

 

posted @ 2021-05-24 13:07  小鲨鱼2018  阅读(206)  评论(0编辑  收藏  举报