freebasic manual - documentation.help · freebasic is a free 32-bit compiler for the basic...
TRANSCRIPT
-
FreeBASICManual
WelcometoFreeBASIC|GettingHelpwithFreeBASIC
LanguageDocumentation
Keywords-AlphabeticalKeywords-FunctionalGraphicsKeywordsOperatorsList
VariablesandDataTypesVariableDeclarationsUserDefinedTypesStandardDataTypesStandardDataTypeLimitsConvertingBetweenDataTypesOperatorsOperatorsOperatorPrecedenceBitwiseOperators&TruthTablesStatementsControlFlowProceduresModularizingOtherPreprocessorEscapeSequencesInStringLiteralsMeta-statementsIntrinsicDefinesErrorHandling
TutorialsProgrammer'sGuideCommunityTutorialsCommunityCodeLibraryExternalLibrariesIndex
UsingtheFreeBASICcompiler
InstallingFreeBASIC|RequirementsRunningFreeBASICUsingtheCommandLine|CommandLineOptions
DebuggingwithFreeBASIC
CompilerErrorMessagesToolsusedbyfbc
FreeBASICdialectsandQBASIC
FreeBASICandQbasic|DifferencesfromQBFreeBASICDialects
FAQs
CompilerFAQGraphicsLibraryFAQ
-
InlineAsm
RuntimeLibraryReference
ArrayFunctionsBitManipulationConsoleFunctionsDateandTimeFunctionsErrorHandlingFunctionsFileIOFunctionsMathematicalFunctionsMemoryFunctionsOperatingSystemFunctionsStringFunctionsThreadingSupportFunctionsUserInputFunctions
GraphicsLibraryReference
2DDrawingFunctionsUserInputFunctionsScreenFunctions
Supportedgraphicsdrivers(backends)KeyboardScanCodesDefaultPalettes
RuntimeLibraryFAQXboxportFAQDOSrelatedFAQWindowsrelatedFAQLinuxrelatedFAQ
Miscellaneous
ObsoleteKeywordsGlossaryMiscellaneousKeywordsCStandardLibraryFunctionsASCIICharacterCodesRuntimeErrorCodesC/C++vs.FreeBASICsyntaxcomparisonC/C++vs.FreeBASICintegerdatatypecomparison
HackingonFreeBASIC
Developer'sTableofContents
Thisdocumentlastcompiled:2016/01/3114:20:41fromhttp://www.freebasic.net/wiki/
-
WelcometoFreeBASIC
Welcometoourworld!Thispageisanoverviewofouronlinewarehouseofknowledge.Enjoyyoursurfingandwehopethiswillbethefirstofmanyvisits.
IntroductionFreeBASICisafree32-bitcompilerfortheBASIClanguage.ItisopensourceandlicensedundertheGPL.ItisdesignedtobesyntaxcompatiblewithQuickBASIC,whileexpandingonthelanguageandcapabilities.ItcancreateprogramsforMS-Windows,DOSandLinux,andisbeingportedtootherplatforms.SeeAboutFreeBASICandMainFeatures.
LatestVersionFreeBASICisabetareleasecompileranddevelopmentisongoing.Witheachfullupdate,manyfeaturesareadded,andbugsfrompreviousreleasesarefixed.Toseethelatestversionavailable,visithttp://sourceforge.net/projects/fbconSourceForge,orhttp://www.freebasic.net/index.php/downloadonFreeBASIC'sofficialwebsite.
RequirementsandInstallationMinimumhardwareislistedontheRequirementspage.VisitourInstallationpageforsettingupFreeBASIConyourcomputer.
RunningFreeBASICisacompilerandassuchisnotpackagedwithanIDE(IntegratedDevelopmentEditor),althoughthereareafewIDE'savailable.ForinformationonusingFreeBASICwithoutanIDE,seeRunning.
CompatibilitywithQuickBASICFreeBASICisdesignedtobesyntaxcompatiblewithQuickBASIC.Forbestcode-compatibilitywithQuickBASIC,theQBdialectcanbeusedwhencompilingsourcecode.SeeFreeBASICDialectsandDifferencesfromQB.
http://sourceforge.net/projects/fbchttp://sourceforge.nethttp://www.freebasic.net/index.php/downloadhttp://www.freebasic.net
-
DocumentationAllofficialdocumentationcanbefoundonlineinthewikiathttp://www.freebasic.net/wiki.Theonlinedocumentationisthemostup-to-dateresourceavailable.Inallcasesitcanberegardedasthecorrectversion.Thedownloadableversionsofthemanualaresnapshotsofthedocumentationavailableataparticulartimeandshouldbemostlycorrectforaspecificreleasedversionofthecompiler.However,wedonotmaintainmultipleversionsofthedocumentationsotheremaybesomediscrepancies.
StartingpointsintheManualTableofContentsGettingHelpwithFreeBASICProgrammer'sGuide
StartingpointsontheWebOfficialWebsiteathttp://www.freebasic.netOfficialForumsathttp://www.freebasic.net/forumOfficialArchiveathttp://www.freebasic.net/arch
ThankyouforusingFreeBASIC.Happycoding!
http://www.freebasic.nethttp://www.freebasic.net/forumhttp://www.freebasic.net/arch
-
GettinghelpwithFreeBASIC
ThereareseveraloptionsavailableforgettinghelpwithFreeBASIC.
TheManualThishugeuser'smanualisfullofinformationthatcanhelpyoulearntowriteprogramsusingFreeBASIC.
Themanualisavailableonlineathttp://www.freebasic.net/wiki.Thereisasearchboxatthebottomofeverypagetohelpyoufindwhatyou'relookingfor.
IfyouareunfamiliarwithFreeBASICorthedocumentation,youmayfindthesepagesagoodplacetostart:
TableofContentsProgrammer'sGuideLibraryHeadersIndexGlossaryCompilerFAQGraphicsLibraryFAQRuntimeLibraryFAQ
Adownloadablemanual(inCHMformat)isavailablefromthesourceforgeprojectpageathttp://sourceforge.net/projects/fbcwhichfeaturesafulltableofcontents,searchingcapabilities,anindex,plusallthesamecontentastheonlineversion.
SearchingthemanualonorofflineisanexcellentplacetostartfindinghelpabouthowtowriteanduseFreeBASICprograms.
ExamplesandSourceCodeInthe./examplesdirectorylocatedwhereFreeBASICwasinstalledonyoursystemarehundredsofexamplestobecompiledandrun.Mostoftheexternallibraryexampleswillneedadditionallibrariestobedownloadedtoallowthemtowork.SeeLibraryHeadersIndexforafulllist.
http://sourceforge.net/projects/fbc
-
FreeBASIC'sofficialcodearchiveislocatedathttp://www.freebasic.net/arch.Thisarchivehostsusercontributedlibrariesandtoolsandhaslinkstosourcecodelocatedonotherwebsites.
TutorialsCommunitycreatedtutorialsaboutFreeBASICcanbefoundatCommunityTutorials.Someselectedtutorialsareincludedinthismanual.
FreeBASICForumAnactivecommunityforumcanbefoundathttp://www.freebasic.net/forumwithseveralsub-forums.Theforumhasasearchfeaturethatcanhelpyoufindanswerstoquestionsorproblemsthatmayhavealreadybeenaskedandsolved.Firstdoasearchforyourproblem,ifyoucan'tfindtheanswerthenpostamessageinoneofthesub-forums.
ChatIRCorInternetRelayChatisagreatwaytochatwiththedevelopersandotherusers,someofwhomareveryknowledgeable.ThereareseveralwaystoconnecttoIRC,ifyouknowwhatyou'redoingsimplyjoin#freebasiconFreeNode.
Ifyouhaven'tthefoggiestwhatIRCisandyouhaveJavainstalled,youcansimplygohere.
Ifyou'retryingtogethelp,themostimportantthingistobepatient.Sometimesyouwon'tgetareplyrightaway.StickaroundorcheckbackandtheCommunitywilltryandassistyou.
http://www.freebasic.net/archhttp://www.freebasic.net/forumhttp://www.freebasic.net/index.php/chat
-
AlphabeticalKeywordsList
Alphabeticallistingofkeywords,macrosandprocedures.
Operators._#$ABCDEFGHIKLMNOPRSTUVWXYZ
OperatorsSeeOperatorList
....
___DATE____Date_Iso____Fb_64Bit____FB_ARGC____FB_ARGV____Fb_Arm____Fb_Asm____Fb_Backend____FB_BIGENDIAN____FB_BUILD_DATE____FB_CYGWIN____FB_DARWIN____FB_DEBUG____FB_DOS____FB_ERR____Fb_Fpmode____Fb_Fpu____FB_FREEBSD____Fb_Gcc____FB_LANG__
KKill
LLBoundLCaseLeftLenLetLibLineLineInputLineInput#LoByteLOCLocalLocateLockLOFLogLongLongIntLoopLoWordLposLPrint
-
__FB_LINUX____FB_MAIN____FB_MIN_VERSION____FB_MT____FB_NETBSD____FB_OPENBSD____FB_OPTION_BYVAL____FB_OPTION_DYNAMIC____FB_OPTION_ESCAPE____FB_OPTION_EXPLICIT____Fb_Option_Gosub____FB_OPTION_PRIVATE____FB_OUT_DLL____FB_OUT_EXE____FB_OUT_LIB____FB_OUT_OBJ____Fb_Pcos____FB_SIGNATURE____FB_SSE____Fb_Unix____Fb_Vectorize____FB_VER_MAJOR____FB_VER_MINOR____FB_VER_PATCH____FB_VERSION____FB_WIN32____FB_XBOX____FILE____FILE_NQ____FUNCTION____FUNCTION_NQ__
LSetLTrim
MMid(Statement)Mid(Function)MinuteMKDMkDirMKIMKLMKLongIntMKSMKShortModMonthMonthNameMultiKeyMutexCreateMutexDestroyMutexLockMutexUnlock
NNakedNameNamespaceNextNewNew(Placement)Next(Resume)NotNow
O
-
__LINE____PATH____TIME__
##Assert#define#else#elseif#endif#endmacro#error#if#ifdef#ifndef#inclib#include#lang#libpath#line#macro#pragma#print#undef
$$Dynamic$Include$Static$Lang
AAbsAbstract(Member)Access
ObjectOctOffsetOfOnErrorOn...GosubOn...GotoOnceOpenOpenComOpenConsOpenErrOpenLptOpenPipeOpenScrnOperatorOption()OptionBaseOptionByValOptionDynamicOptionEscapeOptionExplicitOptionGosubOptionNogosubOptionNoKeywordOptionPrivateOptionStaticOrOr(GraphicsPut)OrElseOutOutput
-
AcosAdd(GraphicsPut)AliasAllocateAlpha(GraphicsPut)AndAndAlsoAnd(GraphicsPut)AnyAppendAsAssertAssertWarnAscAsinAsmAtan2Atn
BBase(Initialization)Base(MemberAccess)BeepBinBinaryBitBitResetBitSetBLoadBooleanBSaveByref(Parameters)Byref(FunctionResults)
OverloadOverride
PPaintPalettepascalPCopyPeekPMapPointPointcoordPointerPokePosPreservePResetPrint?Print#?#PrintUsing?UsingPrivatePrivate:(AccessControl)ProcPtrPropertyProtected:(AccessControl)Pset(Statement)Pset(GraphicsPut)Ptr
-
ByteByVal
CCallCAllocateCaseCastCboolCByteCDblcdeclChainChDirChrCIntCircleClassClearCLngCLngIntCloseClsColorCommandCommonCondBroadcastCondCreateCondDestroyCondSignalCondWaitConstConst(Member)
PublicPublic:(AccessControl)Put(Graphics)Put#(FileI/O)
RRandomRandomizeReadRead(FileAccess)ReadWrite(FileAccess)ReallocateReDimRemResetRestoreResumeResumeNextReturnRGBRGBARightRmDirRndRSetRTrimRun
SSAddScopeScreen
-
Const(Qualifier)ConstructorConstructor(Module)ContinueCosCPtrCShortCSignCSngCsrLinCUByteCUIntCULngCULngIntCUnsgCurDirCUShortCustom(GraphicsPut)CVDCVICVLCVLongIntCVSCVShort
DDataDateDateAddDateDiffDatePartDateSerialDateValue
Screen(Console)ScreenCopyScreenControlScreenEventScreenInfoScreenGLProcScreenListScreenLockScreenPtrScreenResScreenSetScreenSyncScreenUnlockSecondSeek(Statement)Seek(Function)SelectCaseSetDateSetEnvironSetMouseSetTimeSgnSharedShellShlShrShortSinSingleSizeOfSleep
-
DayDeallocateDeclareDefByteDefDbldefinedDefIntDefLngDeflongintDefShortDefSngDefStrDefUByteDefUIntDefulongintDefUShortDeleteDestructorDestructor(Module)DimDirDoDo...LoopDoubleDrawDrawStringDyLibFreeDyLibLoadDyLibSymbol
EElse
SpaceSpcSqrStaticStatic(Member)stdcallStepStickStopStrStrigString(Function)StringStrPtrSubSub(Member)SwapSystem
TTabTanThenThisThreadcallThreadCreateThreaddetachThreadWaitTimeTimeSerialTimeValueTimerTo
-
ElseIfEncodingEnd(Block)End(Statement)EndIfEnumEnvironStatementEnvironEOFEqvEraseErfnErlErmnErrErrorEvent(MessageDataFromScreenevent)ExecExePathExitExpExportExtendsExternExtern...EndExtern
FFalseFieldFileAttrFileCopyFileDateTime
Trans(GraphicsPut)TrimTrueType(Alias)Type(Temporary)Type(Udt)TypeOf
UUBoundUByteUCaseUIntegerUlongULongIntUnionUnlockUnsignedUntilUShortUsing(Print)Using(Namespaces)
Vva_argva_firstva_nextValValLngValIntValUIntValULngVarVarPtr
-
FileExistsFileLenFixFlipForFor...NextFormatFracFreFreeFileFunctionFunction(Member)
GGet(Graphics)Get#(FileI/O)GetJoystickGetKeyGetMouseGoSubGoto
HHexHiByteHiWordHour
IIf...ThenIIfImageConvertRowImageCreateImageDestroyImageInfo
ViewPrintView(Graphics)Virtual(Member)
WWaitWBinWChrWeekdayWeekdayNameWendWhileWhile...WendWHexWidthWindowWindowTitleWInputWithWOctWriteWrite#Write(FileAccess)WSpaceWStrWstring(DataType)Wstring(Function)
XXorXor(GraphicsPut)
YYear
Z
-
ImpImplementsImportInkeyInpInput(Statement)Input(FileI/O)Input#Input$InStrInStrRevIntIntegerIs(SelectCase)Is(Run-TimeTypeInformationOperator)IsDateIsredirected
ZString
-
...(Ellipsis)
Usedinplaceofprocedureparametertopassavariablenumberofarguments,orastheupperboundinanarraydeclarationtodenotethatthenumberofelementswillbedeterminedbytheinitializer.
SyntaxDeclare{Sub|Function}proc_namecdecl(param_list,...){|
Dimarray_symbol([lboundTo]...)[Asdatatype]=>{expression_list
#defineidentifier([parameters,]variadic_parameter...)body
DescriptionTheellipsis(threedots,...)isusedinproceduredeclarationsanddefinitionstoindicateavariableargumentlist.Afirstargument(atleast)mustalwaysbespecifiedandtheproceduremustbecalledwiththeCcallingconventioncdecl.Intheprocedurebody,andva_nextareusedtohandlethevariablearguments.Onlynumerictypesandpointersaresupportedasvariablearguments(allbytesandshortspassedonvariableargumentsareimplicitlyconvertedtointegers,allsinglespassedonvariableargumentsareimplicitlyconvertedtodoubles).Stringscanbepassed,inwhichcaseaZStringPtrtothestringdataistaken.Avariadicprocedurenamecanneverbeoverloaded.
Usinganellipsisinplaceoftheupperboundinanarraydeclarationcausestheupperboundtobesetaccordingtothedatathatappearsintheexpression_list.Whentheellipsisisusedinthismanner,aninitializermustappear,andcannotbeAny.
Usinganellipsisbehindthelastparameterina#defineor#macrodeclarationallowstocreateavariadicmacro.Thismeansitispossibletopassanynumberofargumentstothevariadic_parameter,whichcanbeusedinthebodyasifitwasanormalmacroparameter.Thevariadic_parameterwillexpandtothefulllistofargumentspassedtoit,includingcommas,andcanalsobecompletelyempty.
Example
DeclareFunctionfoocdecl(xAsInteger,...)As
-
DimAsIntegermyarray(0To...)={0,1,2,3}PrintLBound(myarray),UBound(myarray)''0,3
''Usingavariadicmacrotowrapavariadicfunction#include"crt.bi"#defineeprintf(Format,args...)fprintf(stderr,Format,args)eprintf(!"Hellofromprintf:%i%s%i\n",5,"test"
''LISP-likeaccessorsallowingtomodifycomma-separatedlists#definecar(a,b...)a#definecdr(a,b...)b
DifferencesfromQB
NewtoFreeBASIC
Seealso
cdecl
va_arg
va_first
va_next
Dim
Static
#define
-
__DATE__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__DATE__
DescriptionSubstitutesthecompilerdateinaliteralstring("mm-dd-yyyy"format)whereused.
Example
Print"CompileDate:"&__DATE__
CompileDate:09-29-2011
DifferencesfromQB
NewtoFreeBASIC
Seealso
__Date_Iso__
__TIME__
Date
-
__Date_Iso__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__DATE_ISO__
DescriptionSubstitutesthecompilerdateinaliteralstring("yyyy-mm-dd"format)whereused.ThisformatisinlinewithISO8601andcanbeusedforlexicographicaldatecomparisons.
Example
Print"CompileDate:"&__DATE_ISO__
If__DATE_ISO__<"2011-12-25"ThenPrint"CompiledbeforeChristmasday2011"ElsePrint"CompiledafterChristmasday2011"EndIf
CompileDate:2011-09-29CompiledbeforeChristmasday2011
DifferencesfromQB
NewtoFreeBASIC
Seealso
__DATE__
-
__TIME__
Date
-
__Fb_64Bit__
Intrinsicdefinesetbythecompiler
Syntax__FB_64BIT__
DescriptionDefinecreatedatcompiletimeifthethecompilationtargetis64bit,otherwiseundefined.
Example
#ifdef__FB_64BIT__'...instructionsfor64bitOSes...#else'...instructionsforotherOSes#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_FREEBSD__
__FB_OPENBSD__
__FB_NETBSD__
__FB_CYGWIN__
__FB_DARWIN__
__Fb_Pcos__
CompilerOption:-target
-
__FB_ARGC__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_ARGC__
DescriptionSubstitutedwiththenumberofargumentspassedinonthecommandline.
__FB_ARGC__isthenameofaparameterpassedtotheprogram'simplicitmainfunction,andthereforeisonlydefinedinthemodulelevelcodeofthemainmoduleforanapplication.
Example
DimiAsIntegerFori=0To__FB_ARGC__-1Print"arg";i;"='";Command(i);"'"Nexti
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_ARGV__
Command
-
__FB_ARGV__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_ARGV__
DescriptionSubstitutedwithapointertoalistofpointerstothezeroterminatedcommandlineargumentspassedinonthecommandline.
__FB_ARGV__isthenameofaparameterpassedtotheprogram'simplicitmainfunction,andthereforeisonlydefinedinthemodulelevelcodeofthemainmoduleforanapplication.
Example
DeclareFunctionmain_(_ByValargcAsInteger,_ByValargvAsZStringPtrPtr_)AsInteger
Endmain(__FB_ARGC__,__FB_ARGV__)
PrivateFunctionmain_(_ByValargcAsInteger,_ByValargvAsZStringPtrPtr_)AsInteger
DimiAsIntegerFori=0Toargc-1Print"arg";i;"='";*argv[i];"'"Nexti
-
Return0
EndFunction
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_ARGC__
Command
-
__Fb_Arm__
Intrinsicdefinesetbythecompiler
Syntax__FB_ARM__
DescriptionDefinecreatedatcompiletimeifthecompilationtargetusestheARMCPUarchitecture,otherwiseundefined.
Example
#ifdef__FB_ARM__'...instructionsforARMOSes...#else'...instructionsforotherOSes#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_FREEBSD__
__FB_OPENBSD__
__FB_NETBSD__
__FB_CYGWIN__
__FB_DARWIN__
__Fb_Pcos__
CompilerOption:-target
-
__Fb_Asm__
Intrinsicdefinesetbythecompiler
Syntax__FB_ASM__
Description__FB_ASM__returnsastringequalto"intel"or"att"dependingonwhetherinlineassemblyblocksshouldusetheIntelformatortheGCC/AT&T;format.
Example
DimaAsLong#if__FB_ASM__="intel"AsmincdwordPtr[a]EndAsm#elseAsm"incl%0\n":"+m"(a)::EndAsm#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
CompilerOption:-asm
-
__Fb_Backend__
Intrinsicdefinesetbythecompiler
Syntax__FB_BACKEND__
DescriptionDefinedtoeither"gas"or"gcc",dependingonwhichbackendwasspecifiedvia-gen.
DifferencesfromQB
DidnotexistinQB
-
__FB_BIGENDIAN__
Intrinsicdefinesetbythecompiler
Syntax__FB_BIGENDIAN__
DescriptionDefinewithoutavaluecreatedatcompiletimeifcompilingforabigendiantarget.
Itcanbeusedtocompilepartsoftheprogramonlyifthetargetisbigendian.
Example
#ifdef__FB_BIGENDIAN__'...instructionsonlyforbigendianmachines#else'...instructionsonlyforlittleendianmachines#endif
DifferencesfromQB
DidnotexistinQB
-
__FB_BUILD_DATE__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__FB_BUILD_DATE__
DescriptionSubstitutedwiththequotedstringcontainingthedate(MM-DD-YYYY)thecompilerwasbuilton.
Example
Print"Thisprogramcompiledwithacompilerbuiltonthisdate:"
DifferencesfromQB
NewtoFreeBASIC
-
__FB_CYGWIN__
Intrinsicdefinesetbythecompiler
Syntax__FB_CYGWIN__
DescriptionDefinewithoutavaluecreatedatcompiletimeintheCygwinversionofthecompiler,orwhenthe-targetcygwincommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisCygwin.
Example
#ifdef__FB_CYGWIN__'...instructionsonlyforCygwin...#else'...instructionsnotforCygwin...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__Fb_Win32_
__Fb_Unix__
CompilerOption:-target
-
__FB_DARWIN__
Intrinsicdefinesetbythecompiler
Syntax__FB_DARWIN__
DescriptionDefinewithoutavaluecreatedatcompiletimeintheDarwinversionofthecompiler,orwhenthe-targetdarwincommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisDarwin.
Example
#ifdef__FB_DARWIN__'...instructionsonlyforDarwin...#else'...instructionsnotforDarwin...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_WIN32__
__Fb_Unix__
CompilerOption:-target
-
__FB_DEBUG__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_DEBUG__
Description__FB_DEBUG__indicatesifthethegeneratedebuginformationoption'-g'wasspecifiedonthecommandlineatthetimeofcompilation.
Returnsnon-zero(-1)iftheoptionwasspecified.Returnszero(0)otherwise.
Example
#if__FB_DEBUG__0#printDebugmode#else#printReleasemode#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_ERR__
__FB_MT__
CompilerOption:-g
-
__FB_DOS__
Intrinsicdefinesetbythecompiler
Syntax__FB_DOS__
DescriptionDefinewithoutavaluecreatedatcompiletimeifcompilingfortheDOStarget.DefaultintheDOShostedversion,oractivewhenthe-targetdoscommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisDOS.Note:theDOShostedversioncannotcompiletoothertargetsthanDOSbynow.
Example
#ifdef__FB_DOS__'...instructionsonlyforDOS...'...INT0x31#else'...instructionsnotforDOS...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_WIN32__
__Fb_Pcos__
DOSrelatedFAQ
CompilerOption:-target
-
__FB_ERR__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_ERR__
Description__FB_ERR__indicatesif-e,-ex,or-exxwasspecifiedonthecompilercommandlineatthetimeofcompilationofamodule.
Returnsoneofthefollowingvalues:
value description
0 '-e','-ex','-exx'notspecified
1 '-e'wasspecified
3 '-ex'wasspecified
7 '-exx'wasspecified
__FB_ERR__isalwaysdefined.
Example
'Examplecodetodemonstrateauseof__FB_ERR__Dimerr_command_lineAsUByteerr_command_line=__FB_ERR__SelectCaseerr_command_lineCase0Print"NoErrorCheckingenabledontheCommandLine!"Case1Print"SomeErrorCheckingenabledontheCommandLine!"Case3Print"QBasicstyleErrorCheckingenabledontheCommandLine!"Case7Print"ExtremeErrorCheckingenabledontheCommandLine!"
-
CaseElsePrint"SomeUnknownErrorlevelhasbeenset!"EndSelect
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_MT__
__FB_DEBUG__
CompilerOption:-eCompilerOption:-exCompilerOption:-exxErrorHandling
-
__Fb_Fpmode__
Intrinsicdefinesetbythecompiler
Syntax__FB_FPMODE__
DescriptionDefinedas"fast"ifSSEfastarithmeticsisenabled,or"precise"otherwise.
Example
#if__FB_FPMODE__="fast"'...instructionsforusingfast-modemath...#else'...instructionsforusingnormalmath...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
CompilerOption:-fpmode
-
__Fb_Fpu__
Intrinsicdefinesetbythecompiler
Syntax__FB_FPU__
DescriptionDefinedas"sse"ifSSEfloatingpointarithmeticsisenabled,or"x87"otherwise.
Example
#if__FB_FPU__="sse"'...instructionsonlyforSSE...#else'...instructionsnotforSSE...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_SSE__
CompilerOption:-fpu
-
__FB_FREEBSD__
Intrinsicdefinesetbythecompiler
Syntax__FB_FREEBSD__
DescriptionDefinewithoutavaluecreatedatcompiletimeintheFreeBSDversionofthecompiler,orwhenthe-targetfreebsdcommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisFreeBSD.
Example
#ifdef__FB_FREEBSD__'...instructionsonlyforFreeBSD...#else'...instructionsnotforFreeBSD...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_WIN32__
__Fb_Unix__
CompilerOption:-target
-
__Fb_Gcc__
Intrinsicdefinesetbythecompiler
Syntax__FB_GCC__
DescriptionDefinedtotrue(-1)if-gengccisused,orfalse(0)otherwise.
DifferencesfromQB
DidnotexistinQB
-
__FB_LANG__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_LANG__
Description__FB_LANG__indicateswhichlanguagecompatibilityoptionwassetatthetimeofcompilationofamodule.Bydefault__FB_LANG__willbesetto"fb".Thelanguagecompatibilityoptioncanbechangedusingone(ormore)ofthefollowingmethods:
-langcommandlineoption-forcelangcommandlineoption#langdirective$Langmetacommand
Returnsalowercasestringwithoneofthefollowingvalues:
value description
''fb'' FreeBASICcompatibility(default)
''qb'' QBASICcompatibility
''fblite'' FreeBASIClanguagecompatibility,withamoreQBASIC-compatiblecodingstyle
''deprecated'' FBCversion0.16compatibility
__FB_LANG__isalwaysdefined.
Example
''Setoptionexplicitalwayson
#ifdef__FB_LANG__#if__FB_LANG__"fb"
-
OptionExplicit#endif#else''Olderversion-beforelangfbOptionExplicit#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_VERSION__
#lang
CompilerOption:-langCompilerOption:-forcelangCompilerDialects
-
__FB_LINUX__
Intrinsicdefinesetbythecompiler
Syntax__FB_LINUX__
DescriptionDefinewithoutavaluecreatedatcompiletimewhencompilingtotheLinuxtarget.DefaultintheLinuxhostedversionofthecompiler,oractivewhenthe-targetlinuxcommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisLinux.
Example
#ifdef__FB_LINUX__'...instructionsonlyforLinux...'...#libpath"/usr/X11/lib"#else'...instructionsnotforLinux...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_DOS__
__FB_WIN32__
__Fb_Unix__
CompilerOption:-target
-
__FB_MAIN__
Intrinsicdefinesetbythecompiler
Syntax__FB_MAIN__
Description__FB_MAIN__isdefinedinthemainmoduleandnotdefinedinothermodules.
Themainmoduleisdeterminedbythecompileraseitherthefirstsourcefilelistedonthecommandlineorexplicitlynamedusingthe-moptiononthecommandline.
Example
#ifdef__FB_MAIN__#printCompilingthemainmodule#else#printCompilinganadditionalmodule#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
CompilerOption:-m#ifdef
#ifndef
-
__FB_MIN_VERSION__
Macrofunctiontotestminimumcompilerversion
Syntax#define__FB_MIN_VERSION__(major,minor,patch)_((__FB_VER_MAJOR__>major)or_((__FB_VER_MAJOR__=major)and((__FB_VER_MINOR__>minor)or_(__FB_VER_MINOR__=minorand__FB_VER_PATCH__>=patch_level))))
Usage__FB_MIN_VERSION__(major,minor,patch)
Parametersmajorminimummajorversiontotestminorminimumminorversiontotestpatchminimumpatchversiontotest
ReturnValueReturnszero(0)ifthecompilerversionislessthanthespecifiedversion,ornon-zero(-1)ifthecompilerversionisgreaterthanorequaltospecifiedversion
Description__FB_MIN_VERSION__testsforaminimumversionofthecompiler.
Example
#ifNot__FB_MIN_VERSION__(0,18,2)#errorfbcmustbeatleastversion0.18.2TocompileThismodule#endif
-
DifferencesfromQB
NewtoFreeBASIC
Seealso
#if
-
__FB_MT__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_MT__
Description__FB_MT__indicatesifthethemultithreadedoption-mtwasspecifiedonthecommandlineatthetimeofcompilation.
Returnsnon-zero(-1)iftheoptionwasspecified.Returnszero(0)otherwise.
Example
#if__FB_MT__#printUsingmulti-threadedlibrary#else#printUsingSingle-threadedlibrary#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_DEBUG__
CompilerOption:-mt
-
__FB_NETBSD__
Intrinsicdefinesetbythecompiler
Syntax__FB_NETBSD__
DescriptionDefinewithoutavaluecreatedatcompiletimeintheNetBSDversionofthecompiler,orwhenthe-targetnetbsdcommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisNetBSD.
Example
#ifdef__FB_NETBSD__'...instructionsonlyforNetBSD...#else'...instructionsnotforNetBSD...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_WIN32__
__Fb_Unix__
CompilerOption:-target
-
__FB_OPENBSD__
Intrinsicdefinesetbythecompiler
Syntax__FB_OPENBSD__
DescriptionDefinewithoutavaluecreatedatcompiletimeintheOpenBSDversionofthecompiler,orwhenthe-targetopenbsdcommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisOpenBSD.
Example
#ifdef__FB_OPENBSD__'...instructionsonlyforOpenBSD...#else'...instructionsnotforOpenBSD...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_WIN32__
__Fb_Unix__
CompilerOption:-target
-
__FB_OPTION_BYVAL__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OPTION_BYVAL__
DescriptionIndicatesifparameterstoaFunctionorSubarepassedbyreferenceaswithorbyvalueaswithByValbydefaultwhenthebyvalue/byreferencespecifierisnotexplicitlystated.
__FB_OPTION_BYVAL__issettonon-zero(-1)ifbydefaultparametersarepassedvalue,andzero(0)ifbydefaultparametersarepassedbyreference.
ThedefaultforpassingparametersbyreferenceorbyvalueisdeterminedbythelangcommandlineoptionusedduringcompilationorusageofOptionByValsourcefile.
Example
#if(__FB_OPTION_BYVAL__0)#errorOptionByValmustNotbeusedWithThissource#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
ByVal
ByRef
OptionByVal
-
__FB_OPTION_DYNAMIC__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OPTION_DYNAMIC__
Description__FB_OPTION_DYNAMIC__isdefinedastrue(negativeone(-1))ifarecentOptionDynamicstatementor'$Dynamicmeta-commandwasissued.Otherwise,itisdefinedaszero(0).
Example
#if__FB_OPTION_DYNAMIC__0#errorThismodulemustNotuseOptionDynamic#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
OptionDynamic
OptionStatic
-
__FB_OPTION_ESCAPE__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OPTION_ESCAPE__
DescriptionIndicatesifbydefault,stringliteralsareprocessedforescapecharacterswhennotexplicitlyprefixedwiththe$Operatorfornon-escapedstrings,orthe!Operator
ThedefaultmethodforprocessingstringliteralsissetbyusageoftheoptionduringcompilationorusageofOptionEscapeinthesourcefile.
__FB_OPTION_ESCAPE__returnszero(0)iftheoptionhasnotbeenset.Returnsnon-zero(-1)iftheoptionhasbeenset.
Example
#if(__FB_OPTION_ESCAPE__0)#errorOptionEscapemustNotbeusedWithThisincludefile#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
OptionEscape
-
__FB_OPTION_EXPLICIT__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OPTION_EXPLICIT__
Description__FB_OPTION_EXPLICIT__indicatesifOptionExplicithasbeenusedpreviouslyinthesource.
Returnszero(0)iftheoptionhasnotbeenset.Returnsnon-zero(-1)iftheoptionhasbeenset.
Example
#if(__FB_OPTION_EXPLICIT__=0)#errorOptionExplicitmustusedWithThismodule#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
Dim
OptionExplicit
-
__Fb_Option_Gosub__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OPTION_GOSUB__
DescriptionIndicateshowGoSubandReturnwillbehandledatcompiletime.Iftheoptionisset(-1)thenGoSubisallowedandReturnisrecognizedasreturn-from-gosubonly.Iftheoptionisnotset(0)thenGoSubisnotallowedandReturnisrecognizedasreturn-from-procedureonly.
Thismacrovaluecanbechangedatcompiletime.OptionGosubwillsettheoption(enablegosubsupport)andOptionNogosubwillcleartheoption(disablegosubsupport).
__FB_OPTION_GOSUB__returnszero(0)iftheoptionhasnotbeenset.Returnsnon-zero(-1)iftheoptionhasbeenset.
Example
#if(__FB_OPTION_GOSUB__0)''turnoffgosubsupportOptionnogosub#endif
DialectDifferences
Defaultsto-1inthe-langqbdialectand0inallotherdialects.
DifferencesfromQB
NewtoFreeBASIC
-
Seealso
OptionGosub
OptionNogosub
-
__FB_OPTION_PRIVATE__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OPTION_PRIVATE__
DescriptionIndicatesifbydefaultFunction'sandSub'shavemodulescopeorglobalscopewhennotexplicitlyspecifiedwithPrivateorPublic.
ThedefaultscopespecifierforfunctionsandsubsissetbyusageofthecommandlineoptionduringcompilationorusageofOptionPrivateinthesourcefile.
__FB_OPTION_PRIVATE__returnszero(0)iftheoptionhasnotbeenset.zero(-1)iftheoptionhasbeenset.
Example
#if(__FB_OPTION_PRIVATE__0)#errorOptionPrivatemustNotbeusedWithThismodule#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
OptionPrivate
Private
Public
-
__FB_OUT_DLL__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OUT_DLL__
Description__FB_OUT_DLL__indicatesthatthespecifiedoutputfiletypeonthecompilercommandlineatthetimeofcompilationisasharedlibrary.
Returnsnon-zero(-1)iftheoutputisasharedlibrary.Returnszero(0)otherwise.
Onlyoneof__FB_OUT_DLL__,__FB_OUT_EXE__,__FB_OUT_LIB__,or__FB_OUT_OBJ__(-1).Allotherswillevaluatetozero(0).
Example
#if__FB_OUT_DLL__'...specificinstructionswhenmakingasharedlibrary(DLL)#else'...specificinstructionswhennotmakingasharedlibrary(DLL)#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_OUT_EXE__
__FB_OUT_LIB__
__FB_OUT_OBJ__
CompilerOption:-dll
-
__FB_OUT_EXE__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OUT_EXE__
Description__FB_OUT_EXE__indicatesthatthespecifiedoutputfiletypeonthecompilercommandlineatthetimeofcompilationisanexecutable.
Returnsnon-zero(-1)iftheoutputisanexecutable.Returnszero(0)otherwise.
Onlyoneof__FB_OUT_DLL__,__FB_OUT_EXE__,__FB_OUT_LIB__,or__FB_OUT_OBJ__non-zero(-1).Allotherswillevaluatetozero(0).
Example
#if__FB_OUT_EXE__'...specificinstructionswhenmakinganexecutable#else'...specificinstructionswhennotmakinganexecutable#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_OUT_DLL__
__FB_OUT_LIB__
__FB_OUT_OBJ__
-
__FB_OUT_LIB__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OUT_LIB__
Description__FB_OUT_LIB__indicatesthatthespecifiedoutputfiletypeonthecompilercommandlineatthetimeofcompilationisastaticlibrary.
Returnsnon-zero(-1)iftheoutputisastaticlibrary.Returnszero(0)otherwise.
Onlyoneof__FB_OUT_DLL__,__FB_OUT_EXE__,__FB_OUT_LIB__,or__FB_OUT_OBJ__zero(-1).Allotherswillevaluatetozero(0).
Example
#if__FB_OUT_LIB__'...specificinstructionswhenmakingastaticlibrary#else'...specificinstructionswhennotmakingastaticlibrary#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_OUT_EXE__
__FB_OUT_DLL__
__FB_OUT_OBJ__
CompilerOption:-lib
-
__FB_OUT_OBJ__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_OUT_OBJ__
Description__FB_OUT_OBJ__indicatesthatthespecifiedoutputfiletypeonthecompilercommandlineatthetimeofcompilationisanobjectmodule.
Returnsnon-zero(-1)iftheoutputisanobjectmodule.Returnszero(0)otherwise.
Onlyoneof__FB_OUT_DLL__,__FB_OUT_EXE__,__FB_OUT_LIB__,or__FB_OUT_OBJ__Allotherswillevaluatetozero(0).
Example
#if__FB_OUT_OBJ__'...specificinstructionswhencompilingtoanobjectfileonly#else'...specificinstructionswhennotcompilingtoanobjectfileonly#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_OUT_EXE__
__FB_OUT_DLL__
__FB_OUT_LIB__
-
__Fb_Pcos__
Intrinsicdefinesetbythecompiler
Syntax__FB_PCOS__
DescriptionDefinecreatedatcompiletimeiftheOShasfilesystembehaviorstyledlikecommonPCOSes,e.g.DOS,Windows,OS/2,SymbianOS,possiblyothers.Driveletters,backslashes,thatstuff,otherwiseundefined.
Example
#ifdef__FB_PCOS__'...instructionsforPC-ishOSes...#else'...instructionsforotherOSes#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_WIN32__
__FB_DOS__
__FB_XBOX__
__Fb_Unix__
CompilerOption:-target
-
__FB_SIGNATURE__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__FB_SIGNATURE__
DescriptionSubstitutedbyasignatureofthecompilerwhereused.
Example
Print__FB_SIGNATURE__
FreeBASIC0.21.1
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_VERSION__
__FB_WIN32__
__FB_LINUX__
__FB_DOS__
-
__FB_SSE__
Intrinsicdefinesetbythecompiler
Syntax__FB_SSE__
DescriptionDefinewithoutavaluecreatedatcompiletimeifSSEfloatingpointarithmeticsisenabled.
Example
#ifdef__FB_SSE__'...instructionsonlyforSSE...#else'...instructionsnotforSSE...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__Fb_Fpu__
CompilerOption:-fpu
-
__Fb_Unix__
Intrinsicdefinesetbythecompiler
Syntax__FB_UNIX__
DescriptionDefinecreatedatcompiletimeiftheOSisreasonablyenoughlikeUNIXthatyoucancallitUNIX,otherwiseundefined.
Example
#ifdef__FB_UNIX__'...instructionsforUNIX-familyOSes...#else'...instructionsforotherOSes#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_FREEBSD__
__FB_OPENBSD__
__FB_NETBSD__
__FB_CYGWIN__
__FB_DARWIN__
__Fb_Pcos__
CompilerOption:-target
-
__Fb_Vectorize__
Intrinsicdefinesetbythecompiler
Syntax__FB_VECTORIZE__
DescriptionDefinedasthevectorisationlevelnumbersetbythe-veccommand-lineoption.
Example
#if__FB_VECTORIZE__=2'...instructionsonlyforvectorizationlevel2...#else'...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
CompilerOption:-vec
-
__FB_VER_MAJOR__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_VER_MAJOR__
Description__FB_VER_MAJOR__willreturnthemajorversionofFreeBASICcurrentlybeingused.0.90,andwillremain0untilFreeBASICversion1.0isreleased.
Example
DimfbMajorVersionAsIntegerDimfbMinorVersionAsIntegerDimfbPatchVersionAsInteger
fbMajorVersion=__FB_VER_MAJOR__fbMinorVersion=__FB_VER_MINOR__fbPatchVersion=__FB_VER_PATCH__
Print"WelcometoFreeBASIC"&fbMajorVersion&"."
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_VER_MINOR__
__FB_VER_PATCH__
-
__FB_VER_MINOR__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_VER_MINOR__
Description__FB_VER_MINOR__willreturntheminorversionofFreeBASICcurrentlybeingused.ForFreeBASICversion0.90.1,forexample,theminorversionnumberis90.
Example
DimfbMajorVersionAsIntegerDimfbMinorVersionAsIntegerDimfbPatchVersionAsInteger
fbMajorVersion=__FB_VER_MAJOR__fbMinorVersion=__FB_VER_MINOR__fbPatchVersion=__FB_VER_PATCH__
Print"WelcometoFreeBASIC"&fbMajorVersion&"."
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_VER_MAJOR__
__FB_VER_PATCH__
-
__FB_VER_PATCH__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__FB_VER_PATCH__
Description__FB_VER_PATCH__willreturnthepatch/subversion/revisionnumbertheversionofFreeBASICcurrentlybeingused.ForFreeBASIC0.18,forexample,thereweresubversions1,2,3,4,5and6,resultinginversions0.18.1through0.18.6.
Example
DimfbMajorVersionAsIntegerDimfbMinorVersionAsIntegerDimfbPatchVersionAsInteger
fbMajorVersion=__FB_VER_MAJOR__fbMinorVersion=__FB_VER_MINOR__fbPatchVersion=__FB_VER_PATCH__
Print"WelcometoFreeBASIC"&fbMajorVersion&"."
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_VER_MAJOR__
__FB_VER_MINOR__
-
__FB_VERSION__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__FB_VERSION__
DescriptionSubstitutedbytheversionnumberofthecompilerwhereused.
Example
#if__FB_VERSION__<"0.18"#errorPleasecompileWithFBversion0.18Orabove#endif
Thiswillstopthecompilationifthecompilerversionisbelow0.18
DifferencesfromQB
DidnotexistinQB
Seealso
__FB_SIGNATURE__
__FB_WIN32__
__FB_LINUX__
__FB_DOS__
-
__FB_WIN32__
Intrinsicdefinesetbythecompiler
Syntax__FB_WIN32__
DescriptionDefinewithoutavaluecreatedatcompiletimeifcompilingtotheWin32target.DefaultinWin32hostedversion,oractiveifthe-targetwin32commandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisWin32.
Example
#ifdef__FB_WIN32__'...instructionsonlyforWin32...'...GetProcAddress...#else'...instructionsnotforWin32...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_DOS__
__FB_LINUX__
__Fb_Pcos__
CompilerOption:-target
-
__FB_XBOX__
Intrinsicdefinesetbythecompiler
Syntax__FB_XBOX__
DescriptionDefinewithoutavaluecreatedatcompiletimewhenthe-targetxboxcommandlineoptionisused.ItcanbeusedtocompilepartsoftheprogramonlyifthetargetisXbox.
Example
#ifdef__FB_XBOX__'...instructionsonlyforXbox...#else'...instructionsnotforXbox...#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FB_LINUX__
__FB_WIN32__
CompilerOption:-target
-
__FILE__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__FILE__
DescriptionSubstitutedwiththequotedsourcefilenamewhereused.
Anexampleofnormaluseistoreportwrongvaluesindebugging.
Example
DimaAsIntegerIfa
-
__FILE_NQ__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__FILE_NQ__
DescriptionSubstitutedwiththenon-quotedsourcefilenamewhereused.
Example
#print__FILE_NQ__
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FILE__
__FUNCTION_NQ__
__LINE__
-
__FUNCTION__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__FUNCTION__
DescriptionSubstitutedwiththequotednameofthecurrentfunctionblockwhereused.
Itsnormaluseistoreportwrongvaluesindebugging.
If__FUNCTION__isusedatthemodulelevel,thefunctionnamegivenwillbe"__FB_MODLEVELPROC__"foradifferentmodule.
Example
DimaAsInteger
'...
Ifa<0Then''thisshouldn'thappenPrint"Error:a="&a&"in"&__FILE__&EndIf
Error:a=-32767intest.bas(__FB_MAINPROC__)line47
DifferencesfromQB
DidnotexistinQB
Seealso
-
__FILE__
__FUNCTION_NQ__
__LINE__
-
__FUNCTION_NQ__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__FUNCTION_NQ__
DescriptionSubstitutedwiththenon-quotednameofthecurrentfunctionblockwhereused.
If__FUNCTION_NQ__isusedatthemodulelevel,thefunctionnamegivenwillbe__FB_MAINPROC__forthemainmodule,or__FB_MODLEVELPROC__foradifferentmodule.Thisisnottheactualfunctionnamethough,soit'snotasusefulthere.
Example
SubMySubPrint"Addressof"+__FUNCTION__+"is";PrintHex(@__FUNCTION_NQ__)EndSub
MySub
AddressofMYSUBis4012D0
DifferencesfromQB
DidnotexistinQB
Seealso
-
__FILE_NQ__
__FUNCTION__
__LINE__
-
__LINE__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__LINE__
DescriptionSubstitutedwiththecurrentlinenumberofthesourcefilewhereused.
Itsnormaluseistoreportwrongvaluesindebugging.
Example
DimaAsInteger
Ifa<0ThenPrint"Error:a="&a&"in"&__FILE__&EndIf
Error:a=-32767intest.bas(MAIN)line47
DifferencesfromQB
DidnotexistinQB
Seealso
__FILE__
__FUNCTION__
-
__PATH__
Intrinsicdefine(macrostring)setbythecompiler
Syntax__PATH__
DescriptionSettothequotedabsolutepathofthesourcefileatthetimeofcompilation.
Example
'Tellthecompilertoseachthesourcefile's'directoryforlibraries
#libpath__PATH__
DifferencesfromQB
NewtoFreeBASIC
Seealso
__FILE__
-
__TIME__
Intrinsicdefine(macrovalue)setbythecompiler
Syntax__TIME__
DescriptionSubstitutesthecompilertimeinaliteralstring(24clock,"hh:mm:ss"format)whereused.
Example
Print"CompileTime:"&__TIME__
CompileTime:13:42:57
DifferencesfromQB
NewtoFreeBASIC
Seealso
__DATE__
__Date_Iso__
Time
-
#Assert
Preprocessorconditionaldirective
Syntax#assertcondition
ParametersconditionAconditionalexpressionthatisassumedtobetrue
DescriptionAssertsthetruthofaconditionalexpressionatcompiletime.Ifconditionisfalse,compilationwillstopwithanerror.
ThisstatementdiffersfromtheAssertmacrointhat#assertisevaluatedatcompile-timeandAssertisevaluatedatrun-time.
Example
ConstMIN=5,MAX=10#assertMAX>MIN''causeacompile-timeerrorifMAX
-
#define
Preprocessordirectivetodefineamacro
Syntax#defineidentifierbody#defineidentifier([parameters])body#defineidentifier([parameters,]Variadic_Parameter...)body
Description#defineallowstodeclaretext-basedpreprocessormacros.Oncethecompilerhasseena#define,itwillstartreplacingfurtheroccurrencesofidentifierwithbodyTheexpansionisdonerecursively,untilthereisnothingmoretoexpandandthecompilercancontinueanalyzingtheresultingcode.#undefcanbeusedtomakethecompilerforgetabouta#define.
Parametersturnadefineintoafunction-likemacro,allowingtextargumentstobepassedtothemacro.Anyoccurrencesoftheparameternamesinthebodywillbereplacedbythegivenargumenttextduringexpansion.The#Stringizeoperatorcanbeusedonmacroparameterstoturnthemintostringliterals,andthe##Concatenateoperatorcanbeusedtomergetokenstogether.
Note:Inthefunction-likemacrodeclaration,theidentifiershouldbefollowedbytheopeningparentheses(()immediatelywithoutanywhite-spaceinbetween,otherwisethecompilerwilltreatitaspartofthebody.
Definesarescoped;theyareonlyvisibleinthescopetheyweredefinedin.Ifdefinedatmodulelevel,thedefineisvisiblethroughoutthemodule.Iftheidentifierisdefinedinsideacompoundstatementhavingscope(Sub,For..Next,While..Wend,Do..Loop,Scope..EndScopeidentifierdefineisonlyvisiblewithinthatscope.Namespacesontheotherhanddonothaveanyeffectonthevisibilityofadefine.
Identifierscanbecheckedforwith#ifdefandothers,whichcanbeusedtohidepartsofcodefromthecompiler(conditionalcompiling).
Theresultofmacroexpansioncanbecheckedbyusingthe-ppcompileroption.
-
#definesareoftenusedtodeclareconstants.TheConststatementisatype-safealternative.
Example
''Definitionandcheck#defineDEBUGGING#ifdefDEBUGGING'...statements#endif
''Simpledefinition/textreplacement#defineFALSE0#defineTRUE(NotFALSE)
''Function-likedefinition#defineMyRGB(R,G,B)(((R)Shl16)Or((G)Shl8)Or(B))PrintHex(MyRGB(&hff,&h00,&hff))
''Linecontinuationandstatementsinadefinition#defineprintval(bar)_Print#bar;"=";bar
''#definesarevisibleonlyinthescopewheretheyaredefinedScope#defineLOCALDEF1EndScope
#ifndefLOCALDEF#PrintLOCALDEFIsNotdefined#endif
''namespaceshavenoeffectonthevisibilityofadefineNamespacefoo#defineNSDEFEndNamespace
#ifdefNSDEF#PrintNSDEFIsdefined
-
#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
#macro
#PreprocessorStringize
##PreprocessorConcatenate
#ifdef
#undef
Const
...
-
#else
Preprocessorconditionaldirective
Syntax#if(expression)'ConditionallyincludedstatementsifexpressionisTrue#else'ConditionallyincludedstatementsifexpressionisFalse#endif
Description#elsecanbeaddedtoan#if,#ifdef,or#ifndefblocktoprovideanalternateresulttotheconditionalexpression.
Example
#defineMODULE_VERSION1DimaAsString#if(MODULE_VERSION>0)a="Release"#elsea="Beta"#endifPrint"Programis";a
DifferencesfromQB
NewtoFreeBASIC
Seealso
#define
#macro
#if
-
#elseif#endif#ifdef
#ifndef
#undef
defined
-
#elseif
Preprocessorconditionaldirective
Syntax#if(expression1)'Conditionallyincludedstatementsifexpression1isTrue#elseif(expression2)'Conditionallyincludedstatementsifexpression2isTrue#else'Conditionallyincludedstatementsifboth'expression1andexpression2areFalse#endif
Description#elseifcanbeaddedtoan#ifblocktoprovideanadditionalconditions.
Example
#defineWORDSIZE16#if(WORDSIZE=16)'Dosomesome16bitstuff#elseif(WORDSIZE=32)'Dosomesome32bitstuff#else#errorWORDSIZEmustbesetTo16Or32#endif
DifferencesfromQB
NewtoFreebasic
Seealso
#define
-
#macro
#if
#else#endif#ifdef
#ifndef
#undef
defined
-
#endif
Preprocessorconditionaldirective
Syntax#endif
DescriptionEndsagroupofconditionaldirectives
See#if,#ifdef,or#ifndefforexamplesofusage.
Example
#defineDEBUG_LEVEL1#if(DEBUG_LEVEL=1)'Conditionalstatements#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
#define
#macro
#if
#else#elseif#ifdef
#ifndef
#undef
-
defined
-
#Macro...#Endmacro
Preprocessordirectivetodefineamultilinemacro
Syntax#macroidentifier([parameters])body#endmacro
#macroidentifier([parameters,]Variadic_Parameter...)body#endmacro
Description#macroisthemulti-lineversionof#define.
Example
''macroasanexpressionvalue#macroPrint1(a,b)a+b#endmacro
PrintPrint1("Hello","World")
''Output:''HelloWorld!
''macroasmultiplestatements#macroPrint2(a,b)Printa;Print"";Printb;Print"!"#endmacro
-
Print2("Hello","World")
''Output:''HelloWorld!
DifferencesfromQB
NewtoFreeBASIC
Seealso
#define
#ifdef
#undef
-
#error
Preprocessordiagnosticdirective
Syntax#errorerror_text
Parameterserror_textThedisplaymessage
Description#errorstopscompilinganddisplayserror_textwhencompilerfindsit.
Thiskeywordmustbesurroundedbyan#if...#endif,sothecompilercanreach#erroronlyifismet.
Example
#definec1
#ifc=1#errorBadvalueofc#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
#if
#print
-
#Assert
-
#if
Preprocessorconditionaldirective
Syntax#if(expression)'Conditionallyincludedstatements#endif
DescriptionConditionallyincludesstatementsatcompiletime.
Statementscontainedwithinthe#if/#endifblockareincludedifexpressionTrue(non-zero)andexcluded(ignored)ifexpressionevaluatestoFalse(
ThisconditionaldirectivediffersfromtheIfconditionalstatementinthatatcompile-timeandIfisevaluatedatrun-time.
Example
#defineDEBUG_LEVEL1#if(DEBUG_LEVEL>=2)'ThislineisnotcompiledsincetheexpressionisFalsePrint"Startingapplication"#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
#define
#macro
-
#else#elseif#endif#ifdef
#ifndef
#undef
defined
#Assert
-
#ifdef
Preprocessorconditionaldirective
Syntax#ifdefsymbol'Conditionallyincludedstatements#endif
DescriptionConditionallyincludesstatementsatcompiletime.
Statementswithinthe#ifdef...#endifblockareincludedifsymbolisdefinedandexcluded(ignored)ifsymbolisnotdefined.
#ifdefsymbolisequivalentto#ifdefined(symbol)
Example
#define_DEBUG#ifdef_DEBUG'Specialstatementsfordebugging#endif
DifferencesfromQB
NewtoFreebasic
Seealso
#define
#macro
#if
#else
-
#elseif#endif#ifndef
#undef
defined
-
#ifndef
Preprocessorconditionaldirective
Syntax#ifndefsymbol'Conditionallyincludedstatements#endif
DescriptionConditionallyincludesstatementsatcompiletime.
Statementswithinthe#ifndef...#endifblockareincludedifsymbolisnotdefinedandexcluded(ignored)ifsymbolisdefined.
#ifndefsymbolisequivalentto#ifNotdefined(symbol)
Example
#ifndef__MYFILE_BI__#define__MYFILE_BI__'Declarations#endif
DifferencesfromQB
NewtoFreeBASIC
Seealso
#define
#macro
#if
#else
-
#elseif#endif#ifdef
#undef
defined
-
#inclib
Preprocessordirective
Syntax#inclib"libname"
DescriptionIncludesalibraryinthelinkingprocessasiftheuserspecified-llibnamecommandline.
Example
''incompletecodesnippet
''thiswillincludelibmystuff.ainthelinkprocess#inclib"mystuff"
DifferencesfromQB
NewtoFreeBASIC
Seealso
#include
CompilerOption:-lCompilerOption:-p
-
#include
Preprocessorstatementtoincludecontentsofanothersourcefile
Syntax#include[once]"file"
Description#includeinsertssourcecodefromanotherfileatthepointwherethe#includedirectiveappears.Thishastheeffectofcompilingthesourcecodefromtheincludefileasthoughitwerepartofthesourcefilethatincludesit.Oncethecompilerhasreachedtheendoftheincludefile,theoriginalsourcefilecontinuestobecompiled.
Thisisusefultoremovecodefromafileandseparateitintomorefiles.Itisusefultohaveasinglefilewithdeclarationsinaprogramformedbyseveralmodules.Youmayincludefileswithinanincludefile,althoughavoidincludingtheoriginalfileintoitself,thiswillnotproducevalidresults.Typically,includefileswillhaveanextensionof.biandaremainlyusedfordeclaringsubs/functions/variablesofalibrary,butanyvalidsourcecodemaybepresentinanincludefile.
Theoncespecifiertellsthecompilertoincludethefileonlyonceevenifitisincludedseveraltimesbythesourcecode.
$Includeisanalternativeformofinclude,existingonlyforcompatibilitywithQuickBASIC.Itisrecommendedtouse#includeinstead.
Thecompilerwillautomaticallyconvertpathseparatorcharacters('/'and'\')asneededtoproperlyloadthefile.Thefilenamenamemaybeanabsoluteorrelativepath.
Forrelativepaths,orwherenopathisgivenatall,theincludefileissearchforinthefollowingorder:
RelativefromthedirectoryofthesourcefileRelativefromthecurrentworkingdirectory
-
Relativefromadditiondirectoriesspecifiedwiththe-icommandlineoptionTheincludefolderoftheFreeBASICinstallation(FreeBASIC\incwhereFreeBASICisthefolderwherethefbcexecutableislocated)
Example
'header.bifileTypeFooTypeBarAsByteBarbequeAsByteEndType
'main.basfile#include"header.bi"
DimFooAsFooType
Foo.Bar=1Foo.Barbeque=2
DifferencesfromQB
NewtoFreeBASIC
Seealso
#define
#inclib
CompilerOption:-iCompilerOption:-include
-
#lang
Preprocessorstatementtosetthecompilerdialect.
Syntax#lang"lang"
Parameters"lang"Thedialecttoset,enclosedindoublequotes,andmustbeoneof"fb""fblite","qb",or"deprecated".
DescriptionIfthe-forcelangoptionwasnotgivenonthecommandline,#langcanbeusedtosetthedialectforthesourcemoduleinwhichitappears.Atmosttwopasseswillbemadeonthesourcemodule.Onthefirstpass,ifthespecifieddialectisanythingotherthanthedefaultdialect(chosenwith-lang,or"fb"bydefault),thecompilerwillresettheparserforanotherpassandrestartcompilationatthebeginningofthesourcemodule.Ifthisdirectiveisencounteredagainonthesecondpass,andthespecifieddialectdoesnotmatchthenewcurrentdialect,awarningisissuedandcompilationcontinues.Ifanyerrorswereencounteredonthefirstpass,thecompilerwillnotattemptasecondpass."
#langmaynotbeusedinanycompoundstatement,scope,orsubroutine.However,itmaybenestedinmodulelevelpreprocessorstatementsorusedinanincludefile.
Thereiscurrentlynorestrictiononwherethisdirectivemaybeplacedinasourcemodule.Infuturethismaychange,thereforebestpracticewouldbetousethisdirectivebeforethefirstdeclaration,definition,orexecutablestatementinthesource.
Thisdirectiveoverridesthe-langoptionifitwasgivenonthecommandline.However,ifthe-forcelangoptionwasgivenonthecommandline,thisdirectivewillhavenoeffect.Awarningisissued,
-
thedirectiveisignored,andcompilationwillcontinue.Thisallowstheusertoexplicitlyoverride#langdirectives.
Example
#lang"fblite"
DifferencesfromQB
NewtoFreeBASIC
Seealso
$Lang
__FB_LANG__
CompilerOption:-langCompilerOption:-forcelangFreeBASICDialects
-
#libpath
Preprocessorstatementtoaddasearchpathforlibraries
Syntax#libpath"path"
DescriptionAddsalibrarysearchpathtothelinker'slistofsearchpathsasifithadbeenspecifiedonthecommandlinewiththe'-p'option.
Pathsarerelativetotheworkingdirectorywherefbcwasinvokedandnotrelativetothedirectoryofthesourcefile.
Noerrorisgeneratedifthepathdoesnotexistandcompilationandlinkingwillcontinue.
Example
'searchthelibdirectoryforexternallibraries#libpath"lib"
DifferencesfromQB
NewtoFreeBASIC
Seealso
#inclib
#include
CompilerOption:-p
-
#line
Preprocessordirectivetosetthecurrentlinenumberandfilename
Syntax#linenumber["name"]
Parametersnumbernewlinenumber"name"newfilename(optional)
DescriptionInformsthecompilerofachangeinlinenumberandfilenameandupdatesthe__LINE__macrovaluesaccordingly.
Bothcompiletimemessagesandrun-timemessagesareaffectedbythisdirective.
ThisdirectiveallowsotherprogramstogeneratesourcecodefortheFreeBASICcompilerandhaveitreturnwarningand/orerrormessagesthatrefertotheoriginalsourceusedbytheotherprogram.
Example
#line155"outside.src"
Error1000
''Outputis:''Abortingduetoruntimeerror1000atline157ofoutside.src()
DifferencesfromQB
-
NewtoFreeBASIC
Seealso
__FILE__
__LINE__
-
#pragma
Preprocessordirective
Syntax#pragmaoption[=value]Or#pragmapush(option[,value])Or#pragmapop(option)
ParametersPossiblevaluesforoptionandrelatedvalues:
Option Value Description
msbitfields 0 Usebitfieldscompatiblewithgcc(default)
-1(oranyothernon-zerovalue) UsebitfieldscompatiblewiththoseusedinMicrosoftCcompilers
once N/A causethesourcefileinwhichthepragmaappearstobehaveasthoughitwasincludedwith#includeonce...
Ifvalueisnotgiven,thecompilerassumes-1(TRUE).
DescriptionAllowsthesettingofcompileroptionsinsidethesourcecode.
Pushsavesthecurrentvalueoftheoptionontoastack,thenassignsthenewrestorestheoptiontoitspreviousvalue,andremovesitfromthestack.Thismechanismallowsoptionstobechangedforacertainpartofsourcecode,regardlessofthesettingusedbythecontext,whichisespeciallyusefulinside#includeheaderfiles.
Example
''MSVC-
-
compatiblebitfields:savethecurrentsettingandthenenablethem#pragmapush(msbitfields)
''dosomethingthatrequiresMS-compatiblebitfieldshere
''restoreoriginalsetting#pragmapop(msbitfields)
DifferencesfromQB
NewtoFreeBASIC
Seealso
#include
-
#print
Preprocessordiagnosticdirective
Syntax#printtext
DescriptionCausescompilertooutputtexttoscreenduringcompilation.
Example
#printNowcompilingmodulefoo
DifferencesfromQB
NewtoFreeBASIC
Seealso
#error
-
#undef
Preprocessordirectivetoundefineamacro
Syntax#undefsymbol
DescriptionUndefinesasymbolpreviouslydefinedwith#define.
Canbeusedtoensurethatamacroorsymbolhasalimitedlifespananddoesnotconflictwithasimilarmacrodefinitionthatmaybedefinedlaterinthesourcecode.
(Note:#undefshouldnotbeusedtoundefinevariableorfunctionnamesusedinthecurrentfunctionscope.Thenamesareneededinternallybythecompilerandremovingthemcancausestrangeandunexpectedresults.)
Example
#defineADD2(a_,b_)((a_)+(b_))PrintADD2(1,2)'Macronolongerneededsogetridofit...#undefADD2
DifferencesfromQB
NewtoFreebasic
Seealso
#define
#macro
-
#if
#else#elseif#endif#ifdef
#ifndef
defined
-
$Dynamic
Metacommandtochangethewayarraysareallocated
Syntax'$DynamicorRem$Dynamic
Description'$Dynamicisametacommandthatspecifiesthatanyfollowingarraydeclarationsarevariable-length,whethertheyaredeclaredwithconstantsubscriptrangesornot.Thisremainsineffectfortherestofthemoduleinwhich'$Dynamicisused,andcanbeoverriddenwith'$Static.ItisequivalenttotheOptionDynamicstatement.
Example
'compilewith-langfbliteorqb
#lang"fblite"
'$DYNAMICDima(100)'......ReDima(200)
DialectDifferences
Onlyavailableinthe-langfbliteand-langqbdialects.
DifferencesfromQB
Whenusedinsidecommentsitmustbethefirsttoken
-
Seealso
$Static
Dim
ReDim
Erase
OptionDynamic
-
$Include
Metacommandstatementtoincludecontentsofanothersourcefile
Syntax'$Include[once]:'file'orRem$Include[once]:'file'
Description$Includeinsertssourcecodefromanotherfileatthepointwherethe$Includemetacommandappears.Thishastheeffectofcompilingthesourcecodefromtheincludefileasthoughitwerepartofthesourcefilethatincludesit.Oncethecompilerhasreachedtheendoftheincludefile,theoriginalsourcefilecontinuestobecompiled.
Theoncespecifiertellsthecompilertoincludethefileonlyonceevenifitisincludedseveraltimesbythesourcecode.
'$Include:existsforcompatibilitywithQuickBASIC.Itisrecommendedtouse#includeinstead.
Example
'header.bifileTypeFooTypeBarAsByteBarbequeAsByteEndTypeDimFooAsFooType
''compilewith-langfbliteorqb
#lang"fblite"
-
''main.basfile
'$INCLUDE:"header.bi"
Foo.Bar=1Foo.Barbeque=2
DialectDifferences
Onlyavailableinthe-langfbliteand-langqbdialects.
DifferencesfromQB
None
Seealso
#include
-
$Static
Metacommandtochangethewayarraysareallocated
Syntax'$StaticorRem$Static
Description'$Staticisametacommandthatoverridesthebehaviorof$Dynamic,thatis,arraysdeclaredwithconstantsubscriptrangesarefixed-length.Thisremainsineffectfortherestofthemoduleinwhich'$Staticisused,andcanbeoverriddenwith$Dynamic.ItisequivalenttotheOptionStaticstatement.
Example
'compilewith-langfbliteorqb
#lang"fblite"
'$dynamicDima(100)'
-
Seealso
$Dynamic
Dim
Erase
ReDim
OptionDynamic
OptionStatic
-
$Lang
Metacommandstatementtosetthecompilerdialect.
Syntax'$lang:"lang"orRem$lang:"lang"
Parameters"lang"Thedialecttoset,enclosedindoublequotes,andmustbeoneof"fb""fblite","qb",or"deprecated".
DescriptionIfthe-forcelangoptionwasnotgivenonthecommandline,$Langcanbeusedtosetthedialectforthesourcemoduleinwhichitappears.Atmosttwopasseswillbemadeonthesourcemodule.Onthefirstpass,ifthespecifieddialectisanythingotherthanthedefaultdialect(chosenwith-lang,or"fb"bydefault),thecompilerwillresettheparserforanotherpassandrestartcompilationatthebeginningofthesourcemodule.Ifthismetacommandisencounteredagainonthesecondpass,andthespecifieddialectdoesnotmatchthenewcurrentdialect,awarningisissuedandcompilationcontinues.Ifanyerrorswereencounteredonthefirstpass,thecompilerwillnotattemptasecondpass.
$Langmaynotbeusedinanycompoundstatement,scope,orsubroutine.However,itmaybenestedinmodulelevelpreprocessorstatementsorusedinanincludefile.
Thereiscurrentlynorestrictiononwherethisdirectivemaybeplacedinasourcemodule.Infuturethismaychange,thereforebestpracticewouldbetousethisdirectivebeforethefirstdeclaration,definition,orexecutablestatementinthesource.
Thisdirectiveoverridesthe-langoptionifitwasgivenonthe
-
commandline.However,ifthe-forcelangoptionwasgivenonthecommandline,thisdirectivewillhavenoeffect.Awarningisissued,thedirectiveisignored,andcompilationwillcontinue.Thisallowstheusertoexplicitlyoverride$Langmetacommands.
ThismetacommandwasintroducedinFreeBASICversion0.20.0.OlderversionsofFB,andQuickBASIC,willtreatitasacommentandsilentlyignoreit.
Example
'$lang:"qb"
DifferencesfromQB
NewtoFreeBASICQBhandles'$lang:asanormalcomment
Seealso
#lang
__FB_LANG__
CompilerOption:-langCompilerOption:-forcelangFreeBASICDialects
-
Abs
Calculatestheabsolutevalueofanumber
SyntaxDeclareFunctionAbs(ByValnumberAsLong)AsLongDeclareFunctionAbs(ByValnumberAsUlong)AsUlongDeclareFunctionAbs(ByValnumberAsLongInt)AsLongIntDeclareFunctionAbs(ByValnumberAsULongInt)AsULongIntDeclareFunctionAbs(ByValnumberAsDouble)AsDouble
Usageresult=Abs(number)
ParametersnumberValuetofindtheabsolutevalueof.
ReturnValueTheabsolutevalueofnumber.
DescriptionTheabsolutevalueofanumberisitspositivemagnitude.Ifanumberisnegative,itsvaluewillbenegatedandthepositiveresultreturned.Forexample,Abs(-1)andAbs(1)bothreturn1.Therequirednumberargumentcanbeanyvalidnumericexpression.Unsignednumberswillbetreatedasiftheyweresigned,i.e.ifthehighestbitissetthenumberwillbetreatedasnegative,anditsvaluenegated.Thevaluereturnedwillbegreaterthanorequalto0,withtheexceptionofsignedintegerscontainingthelowestpossiblenegativevaluethatcanbestoredinitstype,inwhichcasenegatingitwilloverflowtheresult.
TheAbsunaryOperatorcanbeoverloadedwithuserdefinedtypes.
-
Example
DimnAsInteger
PrintAbs(-1)PrintAbs(-3.1415)PrintAbs(42)PrintAbs(n)
n=-69
PrintAbs(n)
Output:
13.141542069
DialectDifferences
Inthe-langqbdialect,thisoperatorcannotbeoverloaded.
DifferencesfromQB
None
Seealso
Sgn
Operator
-
Abstract
Declareabstractmethods
SyntaxTypetypenameExtendsbase_typenameDeclareAbstractSub|Function|Property|Operator...EndType
DescriptionAbstractisaspecialformofVirtual.Thedifferenceisthatabstractmethodsdonothaveabody,butjustthedeclaration.Essentiallythisallowsthedeclarationofaninterfacewhichcanbeimplementedbyvariousderivedtypes.
Inordertocallanabstractmethod,itmusthavebeenoverriddenandimplementedbyaderiveddatatype,orelsetheprogramwillabort.Asaresult,onlytypesthatimplementalltheabstractmethodsareallowedtocreateobjects.Forthesamereason,aconstructorshouldnotcallanunimplementedmethod.
Constructorscannotbeabstract,sincetheycannotbevirtual.Inaddition,abstractDestructorsarenotsupportedeither,becauseadestructorbody(nomatterwhetherimplicitorexplicit)isneededinordertocallbaseandfielddestructors.
Abstractsarecalled"purevirtual"inC++(unlikeFreeBASIC,C++allowspurevirtualstohaveabody,butaccessibleonlystatically).
Note:Inamulti-levelinheritance,asamenamedmethod(sameidentifierandsignature)canbedeclaredAbstract,Virtualornormal(withoutspecifier)ateachinheritancehierarchylevel.Whenthereismixingofspecifiers,theusualorderisabstract->virtual->normal,fromtoptobottomoftheinheritancehierarchy.Theaccesscontrol(Public/Protected/Private)ofanoverridingmethodisnottakenintoaccountbytheinternalpolymorphismprocess,butonlyfortheinitialcallatcompile-time.
-
Aderivedstaticmethodcannotoverrideabasevirtual/abstractmethod,butcanshadowanybasemethod(includingvirtual/abstract).
Example
TypeHelloextendsobjectDeclareabstractSubhi()EndType
TypeHelloEnglishextendsHelloDeclareSubhi()EndType
TypeHelloFrenchextendsHelloDeclareSubhi()EndType
TypeHelloGermanextendsHelloDeclareSubhi()EndType
SubHelloEnglish.hi()Print"hello!"EndSub
SubHelloFrench.hi()Print"Salut!"EndSub
SubHelloGerman.hi()Print"Hallo!"EndSub
Randomize(Timer())
DimAsHelloPtrh
-
ForiAsInteger=0To9SelectCase(Int(Rnd()*3)+1)Case1h=NewHelloFrenchCase2h=NewHelloGermanCaseElseh=NewHelloEnglishEndSelect
h->hi()DeletehNext
DialectDifferences
Onlyavailableinthe-langfbdialect.
DifferencesfromQB
NewtoFreeBASIC
Seealso
Virtual
Type
Extends
Object
-
Access
ClauseoftheOpenstatementtospecifyrequestedprivileges
SyntaxOpenfilenameforBinaryAccess{Read|Write|ReadWrite}as[#]
UsageopenfilenameforbinaryAccessReadas#filenumopenfilenameforbinaryAccessWriteas#filenumopenfilenameforbinaryAccessReadWriteas#filenum
ParametersReadOpenthefilewithonlyreadprivileges.WriteOpenthefilewithonlywriteprivileges.ReadWriteOpenthefilewithreadandwriteprivileges.
DescriptionAccessisusedwiththeOpenstatementtorequestread,write,orreadandwriteprivileges.Accessclauseisnotspecified,ReadWriteisassumed.
Example
Thisexampleshowshowtoopenthefile"data.raw"withReadandthen"data.out"withaccess,inBinarymode,inanopenfilenumberreturnedbyFreeFile.
DimAsIntegero
''getanopenfilenumber.o=FreeFile''openfileforread-onlyaccess.Open"data.raw"ForBinaryAccessReadAs#o
-
''makeabufferinmemorythatstheentiresizeofthefileDimAsUBytefile_char(LOF(o)-1)
''getthefileintothebuffer.Get#o,,file_char()Close''getanotheropenfilenumber.o=FreeFile''openfileforwrite-onlyaccess.Open"data.out"ForBinaryAccessWriteAs#o
''putthebufferintothenewfile.Put#o,,file_char()Close
Print"Copiedfile""data.raw""tofile""data.out"""
Sleep
DifferencesfromQB
Noneknown.
Seealso
Open
Read
Write
-
Acos
Findsthearccosineofanangle
SyntaxDeclareFunctionAcos(ByValnumberAsDouble)AsDouble
Usageresult=Acos(number)
ParametersnumberAcosinevalueintherange[-1..1].
ReturnValueThearccosineofnumber,inradians,intherange[0..Pi].
DescriptionAcosreturnsthearccosineoftheargumentnumberasaDoublewithintherangeof0totheinverseoftheCosfunction.Thereturnedangleismeasuredinradians
Example
DimhAsDoubleDimaAsDoubleInput"Pleaseenterthelengthofthehypotenuseofatriangle:"Input"Pleaseenterthelengthoftheadjacentsideofthetriangle:"Print""Print"Theanglebetweenthesidesis";Acos(a/Sleep
Theoutputwouldlooklike:
Pleaseenterthelengthofthehypotenuseofatriangle:5
-
Pleaseenterthelengthoftheadjacentsideofthetriangle:4
Theanglebetweenthesidesis0.6435011087932843
DialectDifferences
Notavailableinthe-langqbdialectunlessreferencedwiththealias
DifferencesfromQB
NewtoFreeBASIC
Seealso
Cos
ABriefIntroductionToTrigonometry
-
Add
ParametertothePutgraphicsstatementwhichselectsadditionastheblittingmethod
SyntaxPut[target,][STEP](x,y),source[,(x1,y1)-(x2,y2)],,multiplier]
ParametersAddRequired.multiplierOptionalvaluebetween0and255.Thesourcepixelsarepremultipliedby(multiplier/256)beforebeingadded.Ifomitted,thisvaluedefaultsto255.
DescriptionAddselectsadditionasthemethodforblittinganimagebuffer.Foreachsourceandtargetpixel,thevaluesofeachrespectivecomponentareaddedtogethertoproducetheresult.Theadditionissaturated-i.e.ifthesumofthetwovaluesis256ormore,thenitwillbecroppeddownto255.
Thismethodwillworkinallcolormodes.Maskcolors(color0forindexedimages,magenta(RGB(255,0,255))forfullcolorimages)willbeskipped,thoughfullcolorvaluesof0(RGBA(0,0,0,0))willhavealsohavenoeffect.
Example
''openagraphicswindowScreenRes320,200,16
''createaspritecontainingacircleConstAsIntegerr=32DimcAsAnyPtr=ImageCreate(r*2+1,r*2+Circlec,(r,r),r,RGB(255,255,192),,,1,f
-
''putthespriteatthreedifferentmultipier''levels,overlappingeachotherinthemiddlePut(146-r,108-r),c,add,64Put(174-r,108-r),c,add,128Put(160-r,84-r),c,add,192
''freethememoryusedbythespriteImageDestroyc
''pausetheprogrambeforeclosingSleep
DifferencesfromQB
NewtoFreeBASIC
Seealso
Trans
Alpha
Custom
Put(Graphics)
-
Alias
ClauseoftheSubandFunctionstatementsthatprovidesanalternateinternalname
Syntax[Declare]{Sub|Function}usablenameAlias"alternatename"(...)
UsagedeclaresubusablenameAlias"alternatename"(...)or
declarefunctionusablenameAlias"alternatename"(...)orsubusablenameAlias"alternatename"(...)...endsuborfunctionusablenameAlias"alternatename"(...)...endfunction
DescriptionAliasgivesanalternatenametoaprocedure.Thisalternatenamecannotbeusedwithintheprogramtocalltheprocedure,butitisvisible(ifthefunctionisnotprivate)tothelinkerwhenlinkingwithcodewritteninotherlanguages.
AliasiscommonlyusedforproceduresinlibrarieswritteninotherlanguageswhensuchprocedurenamesarevalidintheotherlanguagebutinvalidinBASIC.WhenusingAliaswithDeclare,onlythealternatenameisusedbythelinker.
Differentlyfromnormalprocedurenames,Aliasdoesnotchangethecaseofthealternatename,soitisusefulwhenexternalcoderequiresanexportedfunctionwithaparticularnameorwithaparticularcase.
Example
IfthereisasubcalledxClearScreeninanexternallibraryandyouwanttoreferenceitwiththenametodoso:
DeclareSubClearVideoScreenAlias"xClearScreen"()
-
AproceduremeanttobeusedbyexternalCcode,exportedasMyExportedProc
FunctionMultiplyByFivecdeclAlias"MyExportedProc"ReturnParameter*5EndFunction
DifferencesfromQB
InQB,AliasonlyworkedwithDeclare.
Seealso
Declare
Export
-
Allocate
Allocatesablockofmemoryfromthefreestore
SyntaxDeclareFunctionAllocatecdecl(ByValcountAsUInteger)AsAny
Usageresult=Allocate(count)
ParameterscountThesize,inbytes,oftheblockofmemorytoallocate.
ReturnValueIfsuccessful,theaddressofthestartoftheallocatedmemoryisreturned.Otherwise,iftherequestedblocksizecouldnotbeallocated,orifcount<0,thenthenullpointer(0)isreturned.
DescriptionAttemptstoallocate,orreserve,countnumberofbytesfromthefreestore(heap).Thenewlyallocatedmemoryisnotinitialized.
Astheinitialvalueofnewlyallocatedmemoryisunspecified,Allocatestring,becausethestringdescriptorbeingnotcleared(containingrandomdata),thatmayinducecorruptedstringormore(tryingtowritetoarandomplaceinmemoryortryingtodeallocatearandompointer).containingstring)touseCAllocate(clearingmemory),orNew(callingconstructor)incaseofexplicitlyclearthedescriptor(settingto0)beforethefirststringuse.
ThepointerthatisreturnedisanAnyPtrandpointstothestartoftheallocatedmemory.Thispointerisguaranteedtobeunique,evenifcountiszero.
Allocatedmemorymustbedeallocated,orreturnedbacktothefreestore,with
Example
-
''ThisprogramusestheALLOCATE(...)functiontocreateabufferof15integersthatis''thenfilledwiththefirst15numbersoftheFibonacciSequence,thenoutputtothe''screen.NotethecalltoDEALLOCATE(...)attheendoftheprogram.
ConstintegerCountAsInteger=15
''Tryallocatingmemoryforanumberofintegers.''DimbufferAsIntegerPtrbuffer=Allocate(integerCount*SizeOf(Integer
If(0=buffer)ThenPrint"Error:unabletoallocatememory,quitting."End-1EndIf
''Primeandfillthememorywiththefibonaccisequence.''buffer[0]=0buffer[1]=1ForiAsInteger=2TointegerCount-1buffer[i]=buffer[i-1]+buffer[i-2]Next
''Displaythesequence.''ForiAsInteger=0TointegerCount-1Printbuffer[i];Next
Deallocate(buffer)End0
Outputis:
01123581321345589144233377
-
Itisimportanttofreeallocatedmemoryifit'snotgoingtobeusedanymore.Unusedmemorythatisn'tfreedissimplywastingmemory,andiftheaddressofthatmemoryissomehowoverwrittenorforgotten,thatmemorycanneverbefreed.Thisconditionisknownasamemoryleak,andshouldbeavoidedatallcosts.Notethatleakedmemoryisalwayscompletelyfreedwhentheapplicationterminates,eitherbyan"ordinary"exitorcrash,sotheleak"persists"onlyaslongastheapplicationruns,neverthelessit'sagoodhabittofreeanyallocatedmemoryinsideyourapplication.Thefollowingexampledemonstratesafunctionwithamemoryleak,wheretheaddressofallocatedmemoryislostandisn'tandcan'tbefreedanymore.Ifsuchafunctioniscalledfrequently,thetotalamountofmemorywastedcanaddupquickly.
''BadexampleofAllocateusage,causingmemoryleaks
SubBadAllocateExample()
DimpAsBytePtr
p=Allocate(420)''assignpointertonewmemory
p=Allocate(420)''reassignsamepointertodifferentmemory,''oldaddressislostandthatmemoryisleaked
Deallocate(p)
EndSub
''MainBadAllocateExample()''CreatesamemoryleakPrint"Memoryleak!"BadAllocateExample()''...andanotherPrint"Memoryleak!"End
PlatformDifferences
Thisprocedureisnotguaranteedtobethread-safe.
DialectDifferences
-
Notavailableinthe-langqbdialectunlessreferencedwiththealias
DifferencesfromQB
NewtoFreeBASIC
Seealso
CAllocate
Reallocate
Deallocate
-
Alpha
ParametertothePutgraphicsstatementwhichselectsalphablendingasthemethod
SyntaxPut[target,][STEP](x,y),source[,(x1,y1)-(x2,y2)],Put[target,][STEP](x,y),source[,(x1,y1)-(x2,y2)],
ParametersAlphaRequired.alphavalOptionalalphaparameterintherange[0..255].Overridesalphavaluesinindividualpixels.
DescriptionAlphaselectsalphablendingasthemethodforPuttinganimage.Iftheeachpixel,andthemaskcolor(magenta)willbetreatedastransparent.
Ifalphavalisnotspecified,Alphawillonlyworkin32-bitcolordepth,andPixelsusingthemaskcolorwillbetreatedasnormal,anddrawnwiththeirgivenalphavalue.
Alphaalsohasanothermodewhichallowsan8-bitimagetobePutontopofa32-bitimage.channelofthe32-bitimagewiththecontentsofthe8-bitimage.
Alphavaluesrangebetween0and255.Analphavalueof0willnotdrawtheimageatall.togetarangebetween2and256,andtheresultisthendividedby256togetavaluebetween1/128and1,whichisusedtocalculatetheexactvalueofeachpixelfromthesourceanddestinationpixels.Thus,255ispracticallyequivalenttodrawingusingPutwithTransblittingmode,0isequivalenttodoingnothingatall,andalltheotheralphavaluesblendisexpected.
ExampleThisexamplecomparesthetwodifferentAlphamodes,includinghowtheyreacttothemaskcolor
''Setupa32-bitscreenScreenRes320,200,32
''Drawcheckeredbackground
-
ForyAsInteger=0To199ForxAsInteger=0To319PSet(x,y),IIf((xShr2XoryShr2)AndNextxNexty
''MakeimagespriteforPuttingDimimgAsAnyPtr=ImageCreate(32,32,RGBA(0,0ForyAsSingle=-15.5To15.5ForxAsSingle=-15.5To15.5DimAsIntegerr,g,b,aIfy
-
''FreetheimagememoryImageDestroyimg
''WaitforakeypressSleep
Thisexampleshowsthespecialmethodforsettinga32-bitalphachannelusingan8-bitimage
DimAsAnyPtrimg8,img32DimAsIntegerx,y,i
''Setupan8-bitgraphicsscreenScreenRes320,200,8Fori=0To255Palettei,i,i,iNextiColor255,0
''Createan8-bitimageimg8=ImageCreate(64,64,0,8)Fory=0To63Forx=0To63DimAsSinglex2=x-31.5,y2=y-31.5DimAsSinglet=Sqr(x2^2+y2^2)/5PSetimg8,(x,y),Sin(t)^2*255NextxNexty
DrawString(16,4),"8-bitAlphasprite"Put(16,16),img8Sleep
-
''Setupa32-bitgraphicsscreenScreenRes320,200,32Fory=0To199Forx=0To319PSet(x,y),IIf(x-yAnd3,RGB(160,160NextxNexty
''Createa32-bit,fullyopaquespriteimg32=ImageCreate(64,64,0,32)Fory=0To63Forx=0To63PSetimg32,(x,y),RGB(x*4,y*4,128)NextxNexty
DrawString(16,4),"OriginalAlphachannel"Put(16,16),img32,Alpha
''Putanewalphachannelusingthe8-bitimagePutimg32,(0,0),img8,Alpha
DrawString(16,104),"NewAlphachannel"Put(16,116),img32,Alpha
''FreethememoryforthetwoimagesImageDestroyimg8ImageDestroyimg32
Sleep
-
DifferencesfromQB
NewtoFreeBASIC
Seealso
Put(Graphics)
Trans
Custom
-
OperatorAnd(Conjunction)
Returnsthebitwise-and(conjunction)oftwonumericvalues
SyntaxDeclareOperatorAnd(ByReflhsAsT1,ByRefrhsAsT2)AsRet
Usageresult=lhsAndrhs
ParameterslhsTheleft-handsideexpression.T1Anynumericorbooleantype.rhsTheright-handsideexpression.T2Anynumericorbooleantype.RetAnumericorbooleantype(varieswithT1andT2).
ReturnValueReturnsthebitwise-and(conjunction)ofthetwooperands.
DescriptionThisoperatorreturnsthebitwise-andofitsoperands,alogicaloperationthatresultsinavaluewithbitssetdependingonthebitsoftheoperands(forconversionofabooleantoaninteger,falseortruebooleanvaluebecomes0or-1integervalue).
Thetruthtablebelowdemonstratesallcombinationsofaboolean-andoperation:
LhsBit RhsBit Result
0 0 0
1 0 0
0 1 0
-
1 1 1
Noshort-circuitingisperformed-bothexpressionsarealwaysevaluated.
Thereturntypedependsonthetypesofvaluespassed.Byte,UByteandfloating-pointtypevaluesarefirstconvertedtoandright-handsidetypesdifferonlyinsignedness,thenthereturntypeisthesameastheleft-handsidetype(thetwotypesisreturned.Onlyiftheleftandright-handsidetypesareboth
Thisoperatorcanbeoverloadedforuser-definedtypes.
Example
'UsingtheANDoperatorontwonumericvaluesDimAsUBytenumeric_value1,numeric_value2numeric_value1=15'00001111numeric_value2=30'00011110
'Result=14=00001110Printnumeric_value1Andnumeric_value2Sleep
'UsingtheANDoperatorontwoconditionalexpressionsDimAsUBytenumeric_value1,numeric_value2numeric_value1=15numeric_value2=25
Ifnumeric_value1>10Andnumeric_value1<20ThenIfnumeric_value2>10Andnumeric_value2<20ThenSleep
'Thiswilloutput"Numeric_Value1isbetween10and20"because'bothconditionsoftheIFstatementistrue'ItwillnotoutputtheresultofthesecondIFstatementbecausethefirst'conditionistrueandthesecondisfalse.
-
DialectDifferences
Inthe-langqbdialect,thisoperatorcannotbeoverloaded.
DifferencesfromQB
None
Seealso
AndAlso
OperatorTruthTables
-
OperatorAndalso(ShortCircuitConjunction)
Returnstheshortcircuit-and(conjunction)oftwonumericvalues
SyntaxDeclareOperatorAndAlso(ByReflhsAsT1,ByRefrhsAsT2)As
Usageresult=lhsAndAlsorhs
ParameterslhsTheleft-handsideexpression.T1Anynumericorbooleantype.rhsTheright-handsideexpression.T2Anynumericorbooleantype.RetAnumericorbooleantype(varieswithT1andT2).
ReturnValueReturnstheshortcircuit-and(conjunction)ofthetwooperands.
DescriptionThisoperatorevaluatesthelefthandsideexpression.Iftheresultiszero,thenzeroisimmediatelyreturned.Iftheresultisnonzerothentherighthandsideisevaluated,andthelogicalresultfromthatisreturned.(forconversionofabooleantoaninteger,falseortruebooleanvaluebecomes0or-1integervalue)
Thetruthtablebelowdemonstratesallcombinationsofashortcircuit-andoperation,the'-'denotesthattheoperandisnotevaluated.
-
LhsValue RhsValue Result
0 - 0
nonzero 0 0
nonzero nonzero -1
Short-circuitingisperformed-onlyexpressionsneededtocalculatetheresultareevaluated.
ThereturntypeisalmostalwaysanInteger,ofthevalue0or-1,denotingfalseandtruerespectively.Exceptiftheleftandright-handsidetypesarebothBooleantypeisalsoBoolean.
Thisoperatorcannotbeoverloadedforuser-definedtypes.
Example
''UsingtheANDALSOoperatortoguardagainstarrayaccess''whentheindexisoutofrange
DimAsIntegerisprime(1To10)={__'123456789100,1,1,0,1,0,1,0,0,0_}
DimAsIntegernInput"Enteranumberbetween1and10:",n
''isprime()arraywillonlybeaccessedifnisinrangeIf(n>=1Andn
-
DifferencesfromQB
ThisoperatorwasnotavailableinQB.
Seealso
OrElse
And
OperatorTruthTables
-
And
ParametertothePutgraphicsstatementwhichusesabit-wiseAndastheblittingmethod
SyntaxPut[target,][STEP](x,y),source[,(x1,y1)-(x2,y2)],
ParametersAndRequired.
DescriptionTheAndmethodcombineseachsourcepixelwiththecorrespondingdestinationpixel,usingthebit-wiseAndfunction.Theresultofthisisoutputasthedestinationpixel.Thismethodworksinallgraphicsmodes.Thereisnomaskcolor,althoughcolorvalueswithallbitsset(255for8-bitpalettemodes,orRGBA(255,255,255,255)infull-colormodes)willhavenoeffect,becauseofthebehaviorofAnd.
Infull-colormodes,eachcomponent(red,green,blueandalpha)iskeptinadiscretesetofbits,sotheoperationcanbemadetoonlyaffectsomeofthechannels,bymakingsuretheallthevaluesoftheotherchannelsaresetto255.
Example
''openagraphicswindowScreenRes320,200,16Line(0,0)-(319,199),RGB(255,255,255),bf
''create3spritescontainingcyan,magentaandyellowcirclesConstAsIntegerr=32DimAsAnyPtrcc,cm,cycc=ImageCreate(r*2+1,r*2+1,RGBA(255,255cm=ImageCreate(r*2+1,r*2+1,RGBA(255,255cy=ImageCreate(r*2+1,r*2+1,RGBA(255,255Circlecc,(r,r),r,RGB(0,255,255),,,1,fCirclecm,(r,r),r,RGB(255,0,255),,,1,f
-
Circlecy,(r,r),r,RGB(255,255,0),,,1,f
''putthethreesprites,overlappingeachotherinthemiddlePut(146-r,108-r),cc,AndPut(174-r,108-r),cm,AndPut(160-r,84-r),cy,And
''freethememoryusedbythespritesImageDestroyccImageDestroycmImageDestroycy
''pausetheprogrambeforeclosingSleep
DifferencesfromQB
None
Seealso
And
Put(Graphics)
-
Any
Anyisusedasaplaceholderforatypeorvalueinvariousways.
SyntaxDimidentifierAsAnyPointer|PtrorDeclareSub|Functionidentifier(ByRefidentifierAsAny[,...])orDimidentifier(Any[,Any...])AsDataTypeor[Declare]{Sub|Function}proc_name(param(Any[,Any...])orDimidentifierAsDataType=AnyorNewDataType(Any)orNew(Address)DataType[count]{Any}orInStr|InStrRev(string,Anysubstring)
Description
Pointers:AspecialpointertypecalledtheAnyPtr(or"AnyPointer")allowspointingtoanyvariabletype.asaninstanceofDataType.PointerarithmeticisallowedonanAnyPtr
ApureAnyPtrhasnotypecheckingbythecompiler.Itcanbeimplicitlyconvertedtoandfromotherpointertypesthroughassignmentorparameterpassing.
Anyonitsownisnotavaliddatatypeforavariable.Also,itisillegaltodereferencean
ThisshouldnotbeconfusedwithVariant,aVisualBasicdatatypewhichcancontainanytypeofvariable.FreeBASICdoesnotprovidenativesupportforaByrefparameters:
Anycanbeusedinprocedureprototypes(inaDeclarestatement)withdeprecatedanditonlyexistsforcompatibilitywithQB.
Arraydimensions:Inarraydeclarations,AnycanbespecifiedinplaceofthearrayboundsinordertocreateadynamicarraywithacertainamountofdimensionsthatisdeterminedbasedonthenumberofAnysspecified(usethesyntaxwithAnyismandatorywhendeclaringadynamicarraymemberinsidea
-
Inparameterdeclarations,Anycanbealsospecifiedinsteadofemptyparenthesisinordertofixtheamountofdimensions.Initialization:
Anycanbeusedasafakeinitializertodisablethedefaultinitializationofvariablestoprogram'sresponsibilitytofillthevariableswithmeaningfuldatabeforereadingit.
ComparisontoC/C++:ThismatchesthebehaviorofavariabledeclarationwithoutinitializationvalueinC/C++.
SimilartoAnyinitializersforvariables,AnycanalsobeusedwiththeNewthatdonothaveconstructors).
Instr/InstrRev:AnycanbeusedwithInStrorInStrRevasaqualifierforthesubstring
Example
DeclareSubecho(ByValxAsAnyPtr)''echowillacceptanypointertype
DimAsIntegera(0To9)=Any''thisvariableisnotinitializedDimAsDoubled(0To4)
DimpAsAnyPtr
DimpaAsIntegerPtr=@a(0)Print"Notinitialized";echopa''passtoechoapointertointeger
DimpdAsDoublePtr=@d(0)Print"Initialized";echopd''passtoechoapointertodouble
p=pa''assigntopapointertointegerp=pd''assigntopapointertodouble
Sleep
Subecho(ByValxAsAnyPtr)DimAsIntegeriFori=0To39
-
'echointerpretsthedatainthepointerasbytesPrintCast(UBytePtr,x)[i]&"";NextPrintEndSub
'ExampleofANYdisablingthevariabletypecheckingDeclareSubecho(ByRefaAsAny)''ANYdisablesthecheckingforthetypeofdatapassedtothefunction
DimxAsSinglex=-15echox''Passingasingletoafunctionthatexpectsaninteger.Thecompilerdoesnotcomplain!!Sleep
Subecho(ByRefaAsInteger)PrintHex(a)EndSub
Dima(Any)AsInteger'1-dimensionaldynamicarrayDimb(Any,Any)AsInteger'2-dimensionaldynamicarrayDimc(Any,Any,Any)AsInteger'3-dimensionaldynamicarray'etc.
'FurtherRedimsorarrayaccessesmusthaveamatchingamountofdimensionsReDima(0To1)AsIntegerReDimb(1To10,2To5)AsIntegerReDimc(0To9,0To5,0To1)AsInteger
DialectDifferences
Notavailableinthe-langqbdialect.
-
DifferencesfromQB
PointersandinitializersarenewtoFreeBASIC.
Seealso
Dim
Declare
-
Append
Specifiestextfiletobeopenedforappendmode
SyntaxOpenfilenameforAppend[Encodingencoding_type][Locklock_type]as[#]filenum
Parametersfilenamefilenametoopenforappendencoding_typeindicatesencodingtypeforthefilelock_typelockingtobeusedwhilethefileisopenfilenumunusedfilenumbertoassociatewiththeopenfile
DescriptionAfilemodeusedwithOpentoopenatextfileforwriting.
ThismodeisusedtoaddtexttoanexistingfilewithPrint#,orcommaseparatedvalueswithWrite#.
Textfilescan'tbesimultaneouslyreadandwritteninFreeBASIC,soifbothfunctionsarerequiredonthesamefile,itmustbeopenedtwice.
filenamemustbeastringexpressionresultinginalegalfilenameinthetargetOS,withoutwildcards.Thefilewillbesoughtforinthepresentdirectory,unlessthefilenamecontainsapath.Ifthefiledoesnotexist,itiscreated.Thepointerissetafterthelastcharacterofthefile.
Encoding_typeindicatestheUnicodeEncodingofthefile,socharactersarecorrectlyread.Ifomitted,"ascii"encodingisdefaulted.Onlylittleendiancharacterencodingsaresupportedatthemoment.
"utf8"
-
"utf16"
"utf32"
"ascii"(thedefault)
Lock_typeindicatesthewaythefileislockedforotherprocesses,itisoneof:
Read-thefilecanbeopenedsimultaneouslybyotherprocesses,butnotforreadingWrite-thefilecanbeopenedsimultaneouslybyotherprocesses,butnotforwritingReadWrite-thefilecannotbeopenedsimultaneouslybyotherprocesses(thedefault)
filenumIsavalidFreeBASICfilenumber(intherange1..255)notbeingusedforanyotherfilepresentlyopen.Thefilenumberidentifiesthefilefortherestoffileoperations.AfreefilenumbercanbefoundusingtheFreeFilefunction.
Example
DimiAsIntegerFori=1To10Open"test.txt"ForAppendAs#1Print#1,"extendingtest.txt"Close#1Next
DifferencesfromQB
None
Seealso
Input(FileMode)
Open
-
Output
(Print|?)#
Write#
-
As
Optionalpartofadeclarationwhichspecifiesadatatype,orpartoftheOpenspecifiesafilehandle.
SyntaxsymbolnameAsdatatype
Open...As#filenumberType...Asdatatype
DescriptionAsisusedtodeclarethetypeofvariables,fieldsorargumentsandisalsousedinthestatementtodeterminethefilehandle.AsisalsousedwiththeType(Alias)toC'stypedefstatement.
Example
''don'ttrytocompilethiscode,theexamplesareunrelatedDeclareSubmySub(XAsInteger,YAsSing