C语言50个小技巧

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>   // 导入bool类型和true/false常量
#pragma once           //防止头文件重复编译

#ifdef __cplusplus
extern "C" {
#endif
//中间添加头文件,就可以C在C++中编译
#ifdef __cplusplus
} 
#endif

typedef unsigned int  uint16;


#define PRINT_HEX_VAR(var) printf("%s:0x%08X\n", #var, var);//将整数转换为16进制

#define likely(x) __builtin_expect(!!(x), 1)               //用于概率非常高和非常低的情况提高代码效率
#define unlikely(x) __builtin_expect(!!(x), 0)

//宏定义一个两个任意类型取最大值的函数
#define MIN(A,B) ({ \
    __typeof__(A) _a = (A); \
    __typeof__(B) _b = (B); \
    _a < _b ? _a : _b; \
})



#define var(left, right) __typeof__(right) left = (right)

#define NUM_OF(arr1)  (sizeof (arr1) / sizeof (*arr1)) //获取数组长度

//打印数组内容
#define PRINT_ARRAY(arr, len) \
do { \
    printf(#arr ":\n"); \
    for (int i = 0; i < len; i++) { \
        printf("%4d", arr[i]); \
    } \
    printf("\n"); \
} while(0)


#define func()  do{func1(); func2();} while(0)

//Debug时输出文件名、函数名、行号等
#define DEBUG_PRINT(fmt, ...) \                        
    fprintf(stderr, "DEBUG: %s:%d:%s(): " fmt "\n", \
            __FILE__, __LINE__, __func__, ##__VA_ARGS__)
            
#define is_power_of_2(n) ((n) != 0 && ((n) & ((n) - 1)) == 0) //判断一个数是不是2的幂(也可以用来其他判断)


void *function();//万能函数指针

static bool isture = true;
static int  arr[10];
static int  a1[5] = {1,2,3,4,5};
static int  b1[5] = {0};
static char arr1[5] = {'0'};
static int  a = 2;
static int  b = 3;
static int  n1 = 16;
static     int arr3[5] = {2,3,4,4,5};


void swap(int *a, int *b);//最好利用地址来传递变量,占用的空间小

//duff写法提高代码执行效率
void send(char *to, char *from, int count) {
    int n = (count + 7) / 8;
    switch(count % 8) {
        case 0: do { *to++ = *from++;
        case 7:      *to++ = *from++;
        case 6:      *to++ = *from++;
        case 5:      *to++ = *from++;
        case 4:      *to++ = *from++;
        case 3:      *to++ = *from++;
        case 2:      *to++ = *from++;
        case 1:      *to++ = *from++;
        } while(--n > 0);
    }
}

//两个数相加的特殊方法
int add(int x,int y)
{
if( y == 0)
return x;
else{
    return add(x^y,(x&y)<<1);
}
}
//sprintf法16进制转换为字符串
void hextostr()
{
    int num = 255;
    int  hex = 0xA0;
    char str[10];
    char hex_str[20];
    sprintf(str, "%X", hex);
    printf("%s\n", str);
    sprintf(hex_str, "%x", num);
    printf("0x%s\n", hex_str);

}

void int_to_hex()
{
    unsigned int player_score = 12345678;
    PRINT_HEX_VAR(player_score);
}

void get_minnumber()
{
 int  c = 4;
 int  d = 2;

 printf("最小值为:%d\n",MIN(c,d));
}
void get_init_varytype()
{

var(s, 2);
printf("s = %d\n",s);
}

void exchange_func()//交换两个数
{

a = a^b;
b = a^b;
a = a^b;
printf("a = %d\nb = %d\n",a,b);

}

void func1()
{
    printf("runing 1\n");
}

void func2()
{
    printf("runing 2\n");
}


typedef struct  {

int a ;

int b ;

char c ;

double d ;

double e ;

} S;

void foo()
{
    DEBUG_PRINT("entering foo");
    /* do some work */
    DEBUG_PRINT("leaving foo");
}

void array_assignment()
{  
    //穿个“马甲”给数组直接赋值
    int* vest = a1; // vest是arr2的“马甲”
    for(int i = 0; i < NUM_OF(b1); i++) {
        b1[i] = *(vest + i);
    }
    for(int i = 0; i < 5; i++) {
        printf("%d \n", b1[i]);
    }
 
}

int main(void) {
    
memset(arr, 5, 4 * sizeof(int));//写入数组元素
     S s = {
     
     .a = 10,
     .c = 'A',
     .d = 2.1
};



   // 遍历数组并输出每个元素的值
    for (int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    func();
if(5[arr] == *(5+arr))
{
     printf("%d\n",arr[2]);
}
printf("c: %c\n", s.c);
printf("a: %d\n", s.a);
printf("d: %.3f\n", s.d);
foo();    

int n = NUM_OF(arr1);
printf("数组个数:%d\n",n);

exchange_func();

if(1 == is_power_of_2(n1))
{
    printf("n = %d是2的幂\n",n1);
}

array_assignment();//两个数组直接赋值操作
get_init_varytype();//获取变量类型或者初始化变量
get_minnumber();//获取两个数之间的最小值
hextostr();
int_to_hex();
printf("num = %d\n",add(a,b));
    int len = NUM_OF(arr1);
    PRINT_ARRAY(arr3, len);
    return 0;
}



#if 0
//C语言操作符
算术操作符:用于进行基本的数学运算,如加、减、乘、除和求余等。例如:

c
int a = 10, b = 3;
int c = a + b; /* 加法 */
int d = a - b; /* 减法 */
int e = a * b; /* 乘法 */
int f = a / b; /* 整数除法 */
int g = a % b; /* 取模运算 */
关系操作符:用于比较两个值的大小关系,返回一个布尔类型的值(真或假)。例如:

c
int x = 5, y = 7;
if (x < y) {
    printf("x is less than y\n");
}
if (x == y) {
    printf("x and y are equal\n");
}
if (x != y) {
    printf("x and y are not equal\n");
}
逻辑操作符:用于连接多个布尔类型的值,返回一个布尔类型的值。例如:

c
int a = 1, b = 0, c = 1;
if (a && b) {
    /* 条件不成立 */
}
if (a || b) {
    /* 条件成立 */
}
if (a && b || c) {
    /* 条件成立 */
}
赋值操作符:用于将一个值赋给变量,返回被赋值的变量。例如:

c
int a = 5, b = 7;
a += b; /* 等价于 a = a + b */
b *= 3; /* 等价于 b = b * 3 */
位操作符:用于对二进制数进行位运算,如按位与、按位或、按位异或、左移和右移等。例如:

c
unsigned char a = 0x0f, b = 0x3c;
unsigned char c = a & b; /* 按位与 */
unsigned char d = a | b; /* 按位或 */
unsigned char e = a ^ b; /* 按位异或 */
unsigned char f = b << 2; /* 左移 */
unsigned char g = b >> 3; /* 右移 */
其他操作符:包括条件操作符、逗号操作符和取地址操作符等。例如:

c
int a = 5, b = 7;
int max = (a > b) ? a : b; /* 条件运算符 */
int sum = (a += b, a); /* 逗号运算符 */
int *ptr = &a; /* 取地址运算符 */
#endif

#if 0
//自动获取变量类型
#define VAR_INT 1
#define VAR_DOUBLE 2
#define VAR_STRING 3

typedef struct {
    int type;
    union {
        int i;
        double d;
        char* s;
    } value;
} variable;

variable get_variable(char* str) {
    variable var;
    if (strchr(str, '.') != NULL) { // 包含小数点,即为double类型
        var.type = VAR_DOUBLE;
        var.value.d = atof(str);
    }
    else if (str[0] >= '0' && str[0] <= '9') { // 以数字开头,即为int类型
        var.type = VAR_INT;
        var.value.i = atoi(str);
    }
    else { // 否则认为是字符串类型
        var.type = VAR_STRING;
        var.value.s = str;
    }
    return var;
}

int main() {
    char* str1 = "123";
    char* str2 = "3.14";
    char* str3 = "hello world";
    variable var1 = get_variable(str1);
    variable var2 = get_variable(str2);
    variable var3 = get_variable(str3);
    printf("var1.type=%d, var1.value.i=%d\n", var1.type, var1.value.i);
    printf("var2.type=%d, var2.value.d=%lf\n", var2.type, var2.value.d);
    printf("var3.type=%d, var3.value.s=%s\n", var3.type, var3.value.s);
    return 0;
}
#endif


#if 0
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef void (*pFunc)(void);

enum val  {
    XXX_VAL_1,
    XXX_VAL_2,
    XXX_VAL_3

};
typedef struct {
    uint32_t val;
    pFunc func;
} tValFunc;

void func1(void)
{
    printf("func1 is called.\n");
}

void func2(void)
{
    printf("func2 is called.\n");
    uint32_t nVal = XXX_VAL_3;
}

void func3(void)
{
    printf("func3 is called.\n");
    uint32_t nVal = XXX_VAL_1;
}

tValFunc valfunc_tb[] = {
    {XXX_VAL_1, func1},
    {XXX_VAL_2, func2},
    {XXX_VAL_3, func3},
};

int main()
{
    uint32_t nVal = XXX_VAL_3; // 这里可以根据实际情况调整值
    int i;

    for(i = 0; i < sizeof(valfunc_tb) / sizeof(tValFunc); i++)
    {
        if(valfunc_tb[i].val == nVal && valfunc_tb[i].func != NULL)
        {
            valfunc_tb[i].func();
            break;
        }
    }

    if(i >= sizeof(valfunc_tb) / sizeof(tValFunc))
    {
        printf("Function not found.\n");
    }

    return 0;
}

#endif


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值