c語言之帶參數的宏定義


1.帶參數的宏定義中,宏名和新參表之間不能有空格,

2.在帶參數的宏定義中,形參參數不分配內存單元,因此不必作類型定義。而宏調用中的實參有具體值,要用它去代換形參,因此必須作類型說明。

#include<stdio.h>
#include<iostream>
#define MAX(a,b) (a>b)?a:b

int main() {
    int x, y, max;
    x = 2;
    y = 3;
    max = MAX(x,y);
    printf("%d\n", max);
    system("pause");
    return 0;
}

3.在宏定義中的形參是標識符,而宏調用中實參可以是表達式。

4.在宏定義中,字符串內的形參通常要用括號括起來以避免出錯。

5.帶參的宏和代餐函數類似,但本質不同,除此之外,把同一表達式用函數處理和用宏處理兩者的結果有可能不同。

普通函數:

#include<stdio.h>
#include<iostream>

int SQ(int y) {
    return ((y) * (y));
}
int main() {
    int i = 1;
    int SQ(int y);
    while (i <= 5) {
        printf("%d ", SQ(i++));
    }
    printf("\n");
    system("pause");
    return 0;
}

輸出:

 

宏定義:

#include<stdio.h>
#include<iostream>
#define SQ(y) (y)*(y)

int main() {
    int i = 1;
    while (i <= 5) {
        printf("%d ", SQ(i++));
    }
    printf("\n");
    system("pause");
    return 0;
}

輸出:

 

為什么結果不同呢?這是因為普通函數調用時,實參傳給形參的是值,而在宏定義時,要用表達式進行替換,即(i++)*(i++),所以I++會被執行兩次。

6.宏定義也可以用來定義多個語句,在宏調用時,把這些語句又代換到源程序內。

#include<stdio.h>
#include<iostream>
#define STR(s1,s2,s3,s4) strcat(strcat(strcat(s4,s3),s2),s1)

int main() {
    char str4[] = "ni ";
    char str3[] = "hao ";
    char str2[] = "a ";
    char str1[] = "!!! ";
    printf("%s\n", STR(str1, str2, str3, str4));
    system("pause");
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM