Skip to content

#MACRO...#ENDMACRO


用于定义多行宏的预处理器指令

语法

#macro identifier [?] ( [ parameters ] )

body

#endmacro

#macro identifier [?] ( [ parameters, ] variadic_parameter... )

body

#endmacro

说明

#macro#define 的多行版本。

如果在定义语法中 identifier 后使用可选的问号(?),带参数的宏可以不使用括号包裹参数进行调用。

注意:注意可能与包含宏名称作为其项之一的表达式产生冲突。

注意:与类函数的 #define 声明不同,在任何宏声明语法中,宏名称与开括号之间可以有空格。

警告:在宏体中,如果参数位于至少有一个运算符的表达式内,可能必须用括号括住任何使用的参数,以避免运算符优先级发生不期望的变化(如果传递的参数是也有运算符的表达式)。

示例

start GeSHi

vb
' macro as an expression value

#macro Print1( a, b )
    a + b
#endmacro

Print Print1( "Hello ", "World!" )

/' Output :
Hello World!
'/

end GeSHi

start GeSHi

vb
' macro as multiple statements

#macro Print2( a, b )
    Print a;
    Print " ";
    Print b;
    Print "!"
#endmacro

Print2( "Hello", "World" )

/' Output :
Hello World!
'/

end GeSHi

start GeSHi

vb
' macro with a variadic parameter

#macro test1( arg1, arg2... )
    Print arg1
    #if #arg2 = ""
        Print "2nd argument not passed"
    #else
        Print arg2
    #endif
#endmacro

test1( "1", "2" )
Print "-----------------------"
test1( "3" )
Print "-----------------------"
test1( 5, 6 )
Print "-----------------------"
test1( 7 )

/' Output :
1
2
-----------------------
3
2nd argument Not passed
-----------------------
 5
 6
-----------------------
 7
2nd argument Not passed
'/

end GeSHi

start GeSHi

vb
' macro with a variadic parameter which can contain several sub-parameters:
'   To distinguish between the different arguments passed by variadic_parameter,
'   you can first convert variadic_parameter to a string using the Operator # (Preprocessor Stringize),
'   then differentiate in this string (#variadic_parameter) each passed argument by locating the separators (usually a comma).

#macro test2( arg1, arg2... )
    Print "'" & Trim(#arg1) & "'"
    Scope
        Dim As String s = Trim(#arg2)
        If s <> "" Then
            Do
                Dim As Integer k = InStr(1, s, ",")
                If k = 0 Then
                    Print "'" & s & "'"
                    Exit Do
                End If
                Print "'" & Left(s, k - 1) & "'"
                s = Trim(Mid(s, k+1))
            Loop
        End If
    End Scope
#endmacro

test2( 5 )
Print "----"
test2( 5,6, 7, , 9, 10, ,,13, 14 )

/' Output :
'5'
----
'5'
'6'
'7'
''
'9'
'10'
''
''
'13'
'14'
'/

end GeSHi

版本

  • 在 fbc 1.08.0 之前,可选的问号(?)不可用。

与 QB 的区别

  • FreeBASIC 新增

另请参阅

  • #define
  • #ifdef
  • #undef

返回 目录

基于 FreeBASIC 官方文档翻译 如有侵权请联系我们删除
FreeBASIC 是开源项目,与微软公司无隶属关系