A C Programming Language Puzzle

原文網址,本文不是完全翻譯,而是自己吸收過後,在寫下此筆記

Problem

有一變數a=12,b=36,請寫出一個c function/macro,回傳3612且不使用算數運算和字串處理的函式.

Token-Pasting Operator

當擴展## macro時,##會將左右兩邊的符號(token),合併為一個符號(token).

#include 
#define merge(a, b) a##b
int main()
{
    int a = 12;
    int b = 36;
    printf("%d ", merge(a, b));
}
// Output: 1234

Solution

有了Token-Pasting Operator,應該不難想出此題的解答

#include 
#define merge(a, b) b##a
int main()
{
    int a = 12;
    int b = 36;
    printf("%d ", merge(a, b));
}
// Output: 3612

Reference

  1. https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html#Concatenation

  2. https://msdn.microsoft.com/en-us/library/09dwwt6y.aspx

你可能感兴趣的:(c++,c)