c语言之变参函数、calloc和布尔类型bool

161 篇文章 10 订阅
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <assert.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>


//c语言之变参函数、calloc和布尔类型bool
void simple_printf(const char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);

    while (*fmt != '\0') {
        if (*fmt == 'd') {
            int i = va_arg(args, int);
            printf("%d\n", i);
        } else if (*fmt == 'c') {
            // note automatic conversion to integral type
            int c = va_arg(args, int);
            printf("%c\n", c);
        } else if (*fmt == 'f') {
            double d = va_arg(args, double);
            printf("%f\n", d);
        } else if (*fmt == 'l') {
            double d = va_arg(args, double);
            printf("%lf\n", d);
        }
        ++fmt;
    }

    va_end(args);
}

//http://zh.cppreference.com/w/c/program
void test_exit()
{
    int a;
    scanf("%d",&a);
    if(a==1)
    {
        abort();
    }else if(a==2)
    {
        exit(EXIT_SUCCESS);
    }else if(a==3)
    {
        //quick_exit();//c99标准
    }else if(a==4)
    {
       // _Exit(EXIT_FAILURE);//c99标准
    }else if(a==5)
    {
       assert(a==6);
    }
}
void test_calloc()
{
    int *p1 = calloc(4, sizeof(int));    // 分配并清零4个int的数组
    int *p2 = calloc(1, sizeof(int[4])); // 等价,直接命名数组类型
    int *p3 = calloc(4, sizeof *p3);     // 等价,免去重复类型名

    if(p2) {
        for(int n=0; n<4; ++n) // 打印数组
            printf("p2[%d] == %d\n", n, p2[n]);
    }

    free(p1);
    free(p2);
    free(p3);

    char* line=calloc(100,sizeof(char));//分配并清零内存
    strcpy(line,"yunshouhu\n");
    printf(line);
    free(line);
}


int test_bool()
{
    bool a=true, b=false;
    printf("%d\n", a&&b);
    printf("%d\n", a||b);
    printf("%d\n", !b);
}

int main(void)
{
    simple_printf("dcffl", 3, 'a', 1.999, 42.5,1024.0);

    test_calloc();
    test_bool();
    test_exit();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值