A C Programming Language Puzzle

来源:互联网 发布:淘宝模特照片处理修腿 编辑:程序博客网 时间:2024/06/16 11:12

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

Problem

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

Token-Pasting Operator

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

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

Solution

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

#include <stdio.h>#define merge(a, b) b##aint 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
0 0