Programming Language Cheat Sheets: General

Strings Mathematics Operators and Symbols [ternary operator] General (Control Flow/Debugging) Dates Objects [Type/TypeFull] New Features Timelines Note: UFL: Universal Function Library, a set of around 100-300 standard functions for all programming languages. Languages do not have to implement anything exactly to the UFL specification, it is a guide. See lower down for further details. Sections: Key Functions Error Handling (try/catch/finally, throw) Loops Keywords / Constants Function Definitions Assign/Declare Single Variables Assign/Declare Multiple Variables Multi-Line Strings File Extensions Sleep/Tick Counts (benchmark tests) Concatenate Strings/Integers The Universal Function Library Project: Details Section: Key Functions UFL: Swap [consider 'Swap(&a, &b)' or 'Swap(a, b)' or a swap statement 'swap a b'][destructuring assignment is unclear when longer variable names are used] AutoHotkey: ___ C++: swap [e.g. std::swap(a, b)] C#: ___ [can use: (a, b) = (b, a)][note: destructuring assignment] Crystal: ___ [can use: a, b = b, a][note: destructuring assignment] Excel: ___ Excel VBA: ___ Go: Java: ___ JavaScript: ___ [can use: [a, b] = [b, a]][note: destructuring assignment] Kotlin: ___ PHP: ___ [can use: [$a, $b] = [$b, $a]][also: list($a, $b) = [$b, $a]][note: destructuring assignment] Python: ___ [can use: a, b = b, a][note: destructuring assignment] R: Ruby: ___ [can use: a, b = b, a][note: destructuring assignment] Rust: ___ [can use: (a, b) = (b, a)][note: destructuring assignment] Swift: swap [e.g. swap(&a, &b)][also: (a, b) = (b, a)][note: destructuring assignment] UFL: Noop AutoHotkey: ___ [can use: {}][note: in some contexts this creates an object] C++: ___ [can use: ;] C#: ___ [can use: ;] Crystal: ___ [can use: nil] Excel: ___ Excel VBA: ___ Go: Java: ___ [can use: ;] JavaScript: ___ [can use: {} (typically with no semicolon)][note: in some contexts this creates an object] Kotlin: ___ PHP: ___ [can use: ;] Python: ___ [can use: pass] R: Ruby: ___ [can use: nil] Rust: ___ [can use: {} (typically with no semicolon)] Swift: ___ UFL: PrintWithNewLine [or PrintLn][print string and a newline character] AutoHotkey: ___ [can use: OutputDebug/MsgBox/ToolTip/TrayTip] C++: std::println(vVar) [also: std::printf(vVar)][note: std::println (C++23)][also: std::cout << vVar << "\n"][also: std::cout << vVar << std::endl] C#: Console.WriteLine(vVar) Crystal: p vVar [also: puts vVar][also: print vVar, "\n"][note: p keyword/p()/puts keyword/puts()][note: p() prints strings as code (e.g. "a\"b"), rather than their appearance (e.g. a"b)][note: puts() doesn't print arrays newline-separated (Ruby does)] Excel: ___ Excel VBA: Debug.Print vVar [note: text is printed to the Immediate Window] Go: fmt.Println(vVar) Java: System.out.println(vVar) JavaScript: console.log(vVar) [also: alert(vVar)] Kotlin: println(vVar) PHP: var_dump($vVar) [also: echo $vVar . "\n"][also: echo $vVar . "<br>"][note: var_dump() always prints a line break, print_r() prints a line break for objects but not values] Python: print(vVar) R: print(vVar) [also: cat(vVar, "\n")][note: print() prints strings as code (e.g. "a\"b"), rather than their appearance (e.g. a"b)] Ruby: p vVar [also: puts vVar][also: print vVar, "\n"][note: p keyword/p()/puts keyword/puts()][WARNING: puts() prints arrays newline-separated][note: p() prints strings as code (e.g. "a\"b"), rather than their appearance (e.g. a"b)] Rust: println!("{}", vVar) Swift: print(vVar) UFL: PrintWithoutNewLine [or PrintNoLn][print string without a line break (newline) character] AutoHotkey: ___ [can use: OutputDebug/MsgBox/ToolTip/TrayTip] C++: std::print(vVar) [note: std::print (C++23)][also: std::cout << vVar] C#: Console.Write(vVar) Crystal: print [note: print keyword/print()][note: print()/p()/puts() print arrays on one line (in Ruby puts() prints arrays newline-separated)] Excel: ___ Excel VBA: Debug.Print vVar; [note: use a semicolon to omit the line break][note: text is printed to the Immediate Window] Go: fmt.Print(vVar) Java: System.out.print(vVar) JavaScript: ___ Kotlin: print(vVar) PHP: echo $vVar [note: echo keyword/echo()/print keyword/print()/var_export() never print a line break, print_r() prints a line break for objects but not values][WARNING: echo/print/print_r print true/false/null as "1"/""/"" (var_dump()/var_export() print true/false/NULL)] Python: print(vVar, end="") R: cat [e.g. cat(vVar)] Ruby: print [note: print keyword/print()][note: print() and p() print arrays on one line] Rust: print!("{}", vVar) Swift: print(vVar, terminator: "") UFL: PrintNewLine [print a line break (newline) character] AutoHotkey: ___ [can use: OutputDebug/MsgBox/ToolTip/TrayTip] C++: std::cout << "\n" C#: Console.WriteLine() Crystal: puts Excel: ___ Excel VBA: Debug.Print Go: fmt.Println() Java: System.out.println() JavaScript: console.log() Kotlin: println() PHP: echo "\n" [also: print "\n"][also: print_r("\n")] Python: print() R: cat("\n") Ruby: puts [also: print "\n"] Rust: println!() [also: println!("")][also: println!("{}", "")] Swift: print() UFL: (PrintCustom) [custom function/macro 'myprint' to print a string (and a line break)] AutoHotkey: myprint := MsgBox C++: #define myprint(vVar) std::cout << (vVar) << "\n" [note: a custom macro] C#: public static void myprint<T>(T vVar) {Console.WriteLine(vVar);} Crystal: def myprint(vVar); p vVar; end Excel: ___ Excel VBA: Function MyPrint(vVar): Debug.Print vVar: End Function Go: Java: public static <T> void myprint(T vVar) {System.out.println(vVar);} JavaScript: myprint = console.log Kotlin: fun myprint(vVar: Any?) : Unit {println(vVar)} [also: val myprint: (Any?)->Unit = ::println] PHP: function myprint($vVar) {var_export($vVar); echo("\n");} Python: myprint = print R: Ruby: def myprint(vVar); p vVar; end Rust: macro_rules! myprint {($vVar:expr)=>{println!("{}", $vVar)}} [e.g. usage: myprint!(vVar)] Swift: func myprint(_ vVar: Any) -> Void {print(vVar)} UFL: Version AutoHotkey: A_AhkVersion C++: __cplusplus C#: ___ Crystal: Crystal::VERSION Excel: INFO("release") Excel VBA: ___ [e.g. #If VBA6 Then][e.g. constants: VBA7/VBA6, Win64/Win32/Mac][also: Application.Version (for the Excel version number)] Go: Java: System.getProperty("java.version") [also: Runtime.version().version().get(0)] JavaScript: ___ Kotlin: KotlinVersion.CURRENT PHP: phpversion() Python: sys.version [requires: import sys] R: Ruby: RUBY_VERSION Rust: ___ Swift: ___ [e.g. #if swift(>=5.9)] UFL: OSVersion AutoHotkey: A_OSVersion C++: ___ C#: Environment.OSVersion Crystal: ___ [can use: Crystal::DESCRIPTION] Excel: INFO("osversion") [e.g. 'Windows (32-bit) NT 6.02'][also: INFO("system") (e.g. 'pcdos')] Excel VBA: Application.OperatingSystem [e.g. 'Windows (32-bit) NT 6.02'][e.g. #If Win64 Then][e.g. constants: Win64/Win32/Mac] Go: Java: System.getProperty("os.name") [also: 'os.version'/'os.arch'] JavaScript: navigator.userAgent [also: navigator.platform] Kotlin: System.getProperty("os.name") [also: 'os.version'/'os.arch'] PHP: php_uname() Python: platform.platform() [also: platform.system()/platform.release()/platform.version()/sys.platform/os.name] R: Ruby: RUBY_PLATFORM Rust: env::consts::OS [requires: use std::env][also: env::consts::FAMILY, env::consts::ARCH] Swift: ProcessInfo().operatingSystemVersion UFL: Sleep [perhaps consider friendly format options e.g. 'm'/'s'] AutoHotkey: Sleep C++: std::this_thread::sleep_for [also: sleep/usleep/nanosleep] C#: System.Threading.Thread.Sleep Crystal: sleep [e.g. 1 sec: sleep 1][also: sleep(1)] Excel: ___ Excel VBA: Application.Wait [e.g. Application.Wait (Now + TimeValue("0:00:01"))][also: the Winapi (kernel32\Sleep)] Go: Java: Thread.sleep [also: TimeUnit.SECONDS.sleep][note: both require a try/catch block] JavaScript: ___ [can use: 'while' and 'new Date()'][can use (inside an async function): await new Promise(r => setTimeout(r, 1000))] Kotlin: Thread.sleep [also: TimeUnit.SECONDS.sleep] PHP: sleep [also: usleep][e.g. 1 sec: sleep(1)][e.g. 1 sec: usleep(1000000)] Python: time.sleep [e.g. 1 sec: sleep(1)][note: sleep accepts fractions of seconds, e.g. 0.5 sec: sleep(0.5)] R: Ruby: sleep [e.g. 1 sec: sleep 1][also: sleep(1)] Rust: thread::sleep [e.g. 1 sec: thread::sleep(time::Duration::from_millis(1000))][requires: use std::{thread, time}] Swift: sleep [also: usleep][e.g. 1 sec: sleep(1)][e.g. 1 sec: usleep(1000000)] UFL: TickCount [get the current time (e.g. in milliseconds) (typically centisecond accuracy, or a higher resolution if possible), take the difference of 2 timestamps to get the time elapsed][e.g. milliseconds since program started, milliseconds since PC switched on] AutoHotkey: ___ [can use: vMSec := A_TickCount (a built-in variable)] C++: std::chrono::system_clock::now [can use: the Winapi (kernel32\GetTickCount64)] C#: DateTime.Now Crystal: Time.local [also: Time.utc] Excel: NOW [e.g. milliseconds: TEXT(NOW()*86400000,"0")][also: TEXT(NOW(),"hh:mm:ss.000")][note: NOW() returns days plus fractions of days][note: Copy, Paste Special..., Values, to lock the date] Excel VBA: Timer [e.g. vSec = Timer][note: seconds plus fractions of seconds] Go: Java: System.currentTimeMillis [also: System.nanoTime] JavaScript: performance.now [e.g. vMSec = performance.now()] Kotlin: System.currentTimeMillis [e.g. vMSec = System.currentTimeMillis()][also: System.nanoTime] PHP: microtime [e.g. $vSec = microtime(true)][note: seconds plus fractions of seconds] Python: time.time [e.g. vSec = time.time][note: seconds plus fractions of seconds] R: Ruby: Time.now Rust: time::SystemTime::now [e.g. time::SystemTime::now()][requires: use std::time] Swift: DispatchTime.now [e.g. vNSec = DispatchTime.now().uptimeNanoseconds][requires: import Foundation] UFL: SetTimer AutoHotkey: SetTimer C++: ___ C#: System.Timers.Timer Crystal: ___ [can use: Thread.new] Excel: ___ Excel VBA: Application.OnTime Go: Java: java.util.Timer JavaScript: setInterval [also: setTimeout] Kotlin: java.util.Timer [also: android.os.Handler] PHP: ___ Python: threading.timer R: Ruby: ___ [can use: Thread.new] Rust: ___ [can use: tokio::spawn] Swift: Timer.scheduledTimer UFL: Assert AutoHotkey: ___ C++: ___ [can use: assert macro] C#: Debug.Assert [also: Trace.Assert] Crystal: should [e.g. vVar.should eq(vValue)][requires: require "spec"] Excel: ___ [can use: can simply type in expressions e.g. '=1=1'][can use: IF] Excel VBA: Debug.Assert Go: Java: ___ [can use: assert keyword] JavaScript: ___ Kotlin: assert [also: assertEquals][WARNING: assertEquals parameter order is 'expected' then 'actual'] PHP: assert Python: ___ [can use: assert statement] R: Ruby: assert_equal [requires: require "test/unit/assertions"][requires: include Test::Unit::Assertions] Rust: assert [e.g. assert!(1==1, "my error message")][also: assert_eq!] Swift: assert Section: Error Handling UFL: Try/Catch/Finally [note: are braces needed for branches] AutoHotkey: try/catch/finally C++: try/catch/___ C#: try/catch/finally Crystal: begin/rescue/ensure/end Excel: ___/___/___ Excel VBA: ___/___/___ [can use: 'On Error Resume Next' (disables error reporting, but the Err object is still updated), 'On Error Goto MyLabel:' (e.g. can be used as a catch block workaround), 'On Error Goto 0' (default, enables error reporting)] Go: Java: try/catch/finally JavaScript: try/catch/finally Kotlin: try/catch/finally PHP: try/catch/finally Python: try/except/finally R: Ruby: begin/rescue/ensure/end Rust: ___/___/___ Swift: do/catch/___ [also: try][also: defer] UFL: Throw AutoHotkey: throw Error("my message") C++: throw std::runtime_error("my message") [note: various classes derive from std::exception][can use (with catch, but not throw): std::exception] C#: throw new Exception("my message") Crystal: raise "my message" Excel: ___ Excel VBA: Err.Raise 1234, , "my message" Go: Java: throw new Exception("my message") [also: Error()] JavaScript: throw new Error("my message") Kotlin: throw Exception("my message") PHP: throw new Exception("my message") Python: raise Exception("my message") R: Ruby: raise "my message" Rust: ___ Swift: ___ [can use: throw NSError(domain:"my message", code:1234)][WARNING: lacks a convenient message field, workaround: use domain field][also: fatalError("my message")][requires (NSError): import Foundation] UFL: Error [(or Exception)] AutoHotkey: Error [note: Exception in AHK v1] C++: std::runtime_error [note: various classes derive from std::exception][can use (with catch, but not throw): std::exception] C#: Exception Crystal: Exception [e.g. raise Exception.new("my message")] Excel: ___ Excel VBA: ___ Go: Java: Exception [also: Error()] JavaScript: Error Kotlin: Exception PHP: Exception [also: ErrorException(), Error()] Python: Exception R: Ruby: StandardError [e.g. raise StandardError.new "my message"] Rust: ___ Swift: ___ [can use: NSError()][also: fatalError()][requires (NSError): import Foundation] UFL: FatalError [end program/script early, e.g. for testing/debugging] AutoHotkey: ExitApp() C++: exit(1) [e.g. 0 for success, non-zero for failure] C#: throw new Exception() [WARNING: this would be caught if within a try block] Crystal: abort Excel: ___ Excel VBA: Exit Sub [note: different from 'End Sub'] Go: Java: System.exit(0) JavaScript: throw "" [WARNING: this would be caught if within a try block] Kotlin: exitProcess(0) [note: import kotlin.system.exitProcess][also (to just throw an exception): throw Exception()] PHP: die Python: raise SystemExit [also: sys.exit()][WARNING: if the current thread is not the main thread, code may still execute] R: Ruby: abort [note: in some situations, 'rescue'/'ensure' blocks can still be executed] Rust: process::exit(1) [requires: use std::process] Swift: fatalError() Section: Loops UFL: LoopCountInc [(or LoopRangeIncDemo)][loop n times (loop from 1 to 10, both inclusive)] AutoHotkey: Loop 10 [note (value): A_Index will contain 1, 2, 3 etc] C++: for (int i=1; i<=10; i++) [note: ++i may be preferable to i++] C#: for (int i=1; i<=10; i++) Crystal: (1..10).each do |i| Excel: ___ Excel VBA: For i = 1 To 10 [afterwards: Next] Go: Java: for (int i=1; i<=10; i++) JavaScript: for (let i=1; i<=10; i++) Kotlin: for (i in 1..10) [note: *doesn't work*: for (i in 1 to 10)][also: for (i in 1.rangeTo(10))] PHP: for ($i=1; $i<=10; $i++) Python: for i in range(1, 10+1): R: Ruby: for i in 1..10 Rust: for i in 1..=10 Swift: for i in 1...10 [also (if i is unused): for _ in 1...10] UFL: LoopCountIncExc [(or (LoopRangeExcDemo)][loop n times (loop from 0 inclusive to 10 exclusive)][i.e. 0 to 9 inclusive] AutoHotkey: ___ [can use: Loop 10][note (value): A_Index-1] C++: for (int i=0; i<10; i++) [note: ++i may be preferable to i++] C#: for (int i=0; i<10; i++) Crystal: (0...10).each do |i| Excel: ___ Excel VBA: For i = 0 To (10 - 1) [note: parentheses unnecessary, for clarity][afterwards: Next] Go: Java: for (int i=0; i<10; i++) JavaScript: for (let i=0; i<10; i++) Kotlin: for (i in 0..<10) [also: for (i in 0 until 10)][also: for (i in 0.rangeUntil(10))] PHP: for ($i=0; $i<10; $i++) Python: for i in range(0, 10): [WARNING: range uses exclusive end] R: Ruby: for i in 0...10 Rust: for i in 0..10 [WARNING: .. uses exclusive end] Swift: for i in 0..<10 [also (if i is unused): for _ in 0..<10] UFL: LoopInfinite [infinite loop (e.g. loop 1 to infinity, infinite range) (an alternative: 0 to infinity)] AutoHotkey: Loop [also: while True][note (value): A_Index will contain 1, 2, 3 etc] C++: for(;;) [also: while(1)][also: for (int i=1;; i++)] C#: for(;;) [also: while(true)][also: for (int i=1;; i++)] Crystal: loop do [also: while true] Excel: ___ Excel VBA: Do While True [afterwards: Loop] Go: Java: for(;;) [also: while(true)][also: for (int i=1;; i++)] JavaScript: for(;;) [also: while(1)][also: for (let i=1;; i++)] Kotlin: while(true) [also: for (i in generateSequence(1){it+1})] PHP: also: for(;;) [also: while(1)][also: for ($i=1;; $i++)] Python: while True: [also: for i in itertools.count(start=1):] R: Ruby: loop do [also: while true] Rust: loop [also: while true] Swift: while true [also: for i in 1...][also (if i is unused): for _ in 1...] Section: Keywords / Constants UFL: IfKeywords [if-statement][note: state if bool/parentheses/braces needed] AutoHotkey: if c / else if c / else [note: parentheses *not* needed] C++: if (c) / else if (c) / else C#: if (c) / else if (c) / else [WARNING: c must be a bool] Crystal: if c / elsif c / else / end [note: parentheses *not* needed] Excel: IF(c,x,y) [note: c must be a bool or numeric] Excel VBA: If c Then / ElseIf c Then / Else / End If [note: c must be a bool or numeric][note: parentheses *not* needed] Go: Java: if (c) / else if (c) / else [WARNING: c must be a bool] JavaScript: if (c) / else if (c) / else Kotlin: if (c) / else if (c) / else [WARNING: c must be a bool][note: can be used in expressions] PHP: if (c) / else if (c) / else Python: if c: / elif c: / else: [note: parentheses *not* needed] R: Ruby: if c / elsif c / else / end [note: parentheses *not* needed] Rust: if c / else if c / else [WARNING: c must be a bool][WARNING: requires braces for 1-line statements][note: can be used in expressions][note: parentheses *not* needed] Swift: if (c) / else if (c) / else [WARNING: c must be a bool][WARNING: requires braces for 1-line statements] UFL: SwitchKeywords [switch statement] AutoHotkey: switch/case/default [note: no fall-through] C++: switch/case/default [note: uses fall-through][WARNING: the input value cannot be a string] C#: switch/case/default [note: no fall-through][WARNING: C# requires 'break' for *every* case/default (i.e. it looks like fall-through is possible, but it is not, the breaks cannot be removed)] Crystal: case/when/else/end [note: no fall-through] Excel: ___/___/___ Excel VBA: Select/Case/Case Else/End Select [note: no fall-through] Go: Java: switch/case/default [note: uses fall-through][also: switch expressions: also switch/case/default (but *no* fall-through)] JavaScript: switch/case/default [note: uses fall-through] Kotlin: when/(pattern)/else [note: no fall-through] PHP: switch/case/default [note: uses fall-through] Python: match/case/case _ [note: no fall-through] R: Ruby: case/when/else/end [note: no fall-through] Rust: match/(pattern)/_ [note: no fall-through][note: must be exhaustive (i.e. all possible values must be covered) (workaround: add a default case)] Swift: switch/case/default [note: no fall-through][note: must be exhaustive (i.e. all possible values must be covered) (workaround: add a default case)] UFL: Null [note: to delete a variable, see VarDelete/ObjectDelRef] AutoHotkey: unset [note: case-insensitive] C++: nullptr [note: NULL macro expands to 0][also (functions): void] C#: null [also (functions): void] Crystal: nil Excel: #NULL! [e.g. type '#NULL!' or '=A1 A2' or '=SUM(A1 A2)' into a cell][note: use ERROR.TYPE() to get the error type] Excel VBA: Nothing [note: also Empty/Null][e.g. Set vVar = Nothing][e.g. vVar = Empty][e.g. vVar = Null][e.g. obtain Empty: a variable that hasn't been used yet/ReDim an array then get a value/store the result of a function with no return value] Go: Java: null [also (functions): void] JavaScript: null [also: undefined][also (array values): 'elided'/'empty'][also: void operator] Kotlin: null [also: Nothing][also (functions): Unit][note: Void is a Java class (with no special meaning in Kotlin)] PHP: null [note: case-insensitive] Python: None [also: del statement] R: Ruby: nil Rust: ___ [also (options): None][e.g. vNone: Option<i32> = None] Swift: nil [also (functions): Void] UFL: IsNull [see also: Null/Array.KeyIsEmpty/FuncVoidType] AutoHotkey: vIsNull = !IsSet(vVar) C++: ___ [e.g. (std::string): vIsNull = (vVar == (std::string)NULL)][WARNING: NULL is defined as 0, so for many types, e.g. int, comparing with null is actually comparing with 0] C#: vIsNull = (vVar == null) Crystal: vIsNull = vVar.nil? [also: vIsNull = (vVar == nil)] Excel: =ERROR.TYPE(A1)=1 Excel VBA: ___ [e.g. (TypeName(vVar) = "Nothing")][e.g. (TypeName(vVar) = "Empty")][e.g. (TypeName(vVar) = "Null")][also (throws if vVar is not an object): vIsNull = vVar Is Nothing] Go: Java: var vIsNull = (vVar == null) JavaScript: vIsNull = (vVar === null) [also (is undefined): (vVar == undefined)][also (is undefined): (typeof vVar == "undefined")][WARNING: vVar == null returns true for null *and undefined*] Kotlin: vIsNull = (vVar == null) [also: vVar is Nothing?] PHP: $vIsNull = is_null($vVar) [also: !isset($vVar)][also: ($vVar == null)] Python: vIsNull = (vVar == None) [also: vVar is None] R: Ruby: vIsNull = vVar.nil? [also: vIsNull = (vVar == nil)] Rust: vIsNull = vVar == None [e.g. test options] Swift: vIsNull = (vVar == nil) UFL: VarDelete [see also: ObjectDelRef][note: typically: deleting an object instance deletes 1 reference, and only when the last reference is deleted, is the object deleted] AutoHotkey: vVar := unset [note: in AHK v1: 'vVar := ""' and 'vVar := 0' were common] C++: delete vVar [also: delete[] vVar][note: 'delete'/'delete[]' must be used for variables created with 'new'][note: 'free' must be used for variables created with 'malloc'] C#: vVar = null Crystal: vVar = nil Excel: ___ Excel VBA: Set vVar = Nothing [note: doesn't work with all types] Go: Java: vVar = null JavaScript: vVar = null [also: vVar = undefined][also: void operator] Kotlin: vVar = null PHP: unset($vVar) [also: $vVar = null][note: unset() sets contents to null] Python: del vVar [also: vVar = None] R: Ruby: vVar = nil Rust: drop(vVar) Swift: vVar = nil UFL: Import [(or Include)] AutoHotkey: #Include [also: #IncludeAgain] C++: #include [e.g. #include <iostream>][e.g. #include <string>][e.g. #include <map>] C#: using [e.g. using System][e.g. using System.Linq][e.g. using System.Collections.Generic] Crystal: require [also: include/extend] Excel: ___ Excel VBA: ___ [can use: Workbooks.Open and Run] Go: Java: import [e.g. import java.util.*][e.g. import java.util.stream.*] JavaScript: import [also: <script src="MyFile.js"></script>] Kotlin: import PHP: include [also: require/include_once/require_once] Python: import [e.g. import sys][e.g. from functools import reduce] R: Ruby: require [also: include/extend] Rust: use [e.g. use std::time] Swift: import [e.g. import Foundation] Section: Function Definitions UFL: FuncBelow [functions can be defined below where they are called] AutoHotkey: yes C++: yes [note: functions must be defined above where they are called (workaround: *declare* the function above where it is called)] C#: yes Crystal: yes Excel: yes Excel VBA: yes Go: Java: yes JavaScript: yes Kotlin: no [WARNING: functions must be defined above where they are called] PHP: yes Python: no [WARNING: functions must be defined above where they are called] R: Ruby: no [WARNING: functions must be defined above where they are called] Rust: yes Swift: yes UFL: FuncMutable [function parameters are mutable][i.e. can a parameter variable be overwritten] AutoHotkey: yes C++: yes C#: yes Crystal: yes Excel: yes Excel VBA: yes Go: Java: yes JavaScript: yes Kotlin: no [WARNING: function parameter values (not object members) are read-only (they are not mutable) (workaround: do 'var vMyParamVar = vMyParamVar' to create a local copy, but it leaves a warning)] PHP: yes Python: yes R: Ruby: yes Rust: no [WARNING: function parameter values (not object members) are read-only (they are not mutable) (workaround: do 'let mut vMyParamVar = vMyParamVar' to create a local copy)] Swift: yes [WARNING: function parameter values (not object members) are read-only (they are not mutable) (workaround: do 'var vMyParamVar = vMyParamVar' to create a local copy)] UFL: FuncVoidType [return type in function definition, for function with no return value] AutoHotkey: ___ C++: void C#: void Crystal: ___ [can use: Nil][can use: Void][note: types can be omitted] Excel: ___ Excel VBA: ___ Go: Java: void JavaScript: ___ Kotlin: Unit PHP: ___ Python: ___ R: Ruby: ___ Rust: ___ [can use: '()', the unit type][note: '()' can be omitted] Swift: Void UFL: FuncPassName [use function by name as a function call parameter][e.g. pass a sort comparator function, e.g. pass a function to map/reduce/filter] AutoHotkey: MyFunc [note: AHK v1: "MyFunc", also: Func("MyFunc")] C++: ::MyFunc [also: MyFunc][note: '::MyFunc' calls function if it exists, 'MyFunc' calls variable if it exists, else function if it exists] C#: MyFunc Crystal: &->MyFunc [e.g. &->MyFunc(Int32,Int32)] Excel: ___ Excel VBA: "MyFunc" [e.g. Application.Run("MyFunc")][note: Application.Run works on custom, but not built-in functions] Go: Java: MyClass::MyFunc JavaScript: MyFunc Kotlin: ::MyFunc PHP: "MyFunc" Python: MyFunc R: Ruby: :MyFunc [e.g. method(:MyFunc)] Rust: MyFunc Swift: MyFunc

UFL: AddCustom/SumCustom [custom 'Add' and 'Sum' functions]

[AutoHotkey]

Add(vNum1, vNum2)
{
	return vNum1 + vNum2
}

Sum(oParams*)
{
	vSum := 0
	for _, vValue in oParams
		vSum += vValue
	return vSum
}

[C++]

int Add(int vNum1, int vNum2)
{
	return vNum1 + vNum2;
}

//WARNING: C++ doesn't have variadic functions, so accept a vector instead:
int Sum(std::vector<int> oVec)
{
	int vSum = 0;
	for (const auto& vValue : oVec)
		vSum += vValue;
	return vSum;
}

[C#]

public static int Add(int vNum1, int vNum2)
{
	return vNum1 + vNum2;
}

public static int Sum(params int[] oParams)
{
	int vSum = 0;
	for (var i=0; i<oParams.Length; i++)
		vSum += oParams[i];
	return vSum;
}

[Crystal]

#MAJOR WARNING: Crystal forces function names (method names) to start with a lower-case letter:

def add(vNum1, vNum2)
	return vNum1 + vNum2
end

def sum(*oParams)
	vSum = 0
	oParams.each do |vValue|
		vSum += vValue
	end
	return vSum
end

[Excel]

//note: this can be used in sheet formulae (it accepts 2 parameters):
//e.g. =MyAdd(A1,A2)
Function MyAdd(vNum1, vNum2)
	MyAdd = vNum1 + vNum2
End Function

//note: this can be used in sheet formulae (it accepts 1 parameter, which can be a range):
//e.g. =MySum(A1:A10)
Function MySum(oParams)
	vSum = 0
	For Each vValue In oParams
		vSum = vSum + vValue
	Next
	MySum = vSum
End Function

[Excel VBA]

Function Add(vNum1, vNum2)
	Add = vNum1 + vNum2
End Function

Function Sum(ParamArray oParams())
	vSum = 0
	For Each vValue In oParams
		vSum = vSum + vValue
	Next
	Sum = vSum
End Function

[Go]

// MAJOR WARNING: Golang demands K&R style indentation:
// WARNING: Golang online compiler enforces a space after the comment symbol ('//'):

func Add(vNum1 int, vNum2 int) int {
	return vNum1 + vNum2
}

func Sum(oParams ...int) int {
	vSum := 0
	for _, vValue := range oParams {
		vSum += vValue
	}
	return vSum
}

[Java]

static int Add(int vNum1, int vNum2)
{
	return vNum1 + vNum2;
}

static int Sum(int... oParams)
{
	int vSum = 0;
	for (var i=0; i<oParams.length; i++)
		vSum += oParams[i];
	return vSum;
}

[JavaScript]

function Add(vNum1, vNum2)
{
	return vNum1 + vNum2;
}

function Sum(...oParams)
{
	vSum = 0;
	for (var i=0; i<oParams.length; i++)
		vSum += oParams[i];
	return vSum;
}

[Kotlin]

fun Add(vNum1: Int, vNum2: Int) : Int
{
	return vNum1 + vNum2
}

fun Sum(vararg oParams: Int) : Int
{
	var vSum = 0
	for (i in 0 until oParams.size)
		vSum += oParams[i]
	return vSum
}

[PHP]

function Add($vNum1, $vNum2)
{
	return $vNum1 + $vNum2;
}

function Sum(...$oParams)
{
	$vSum = 0;
	foreach($oParams as $vValue)
		$vSum += $vValue;
	return $vSum;
}

[Python]

def Add(vNum1, vNum2):
	return vNum1 + vNum2

def Sum(*oParams):
	vSum = 0
	for vValue in oParams:
		vSum += vValue
	return vSum

[R]

Add <- function(vNum1, vNum2)
{
	return (vNum1 + vNum2)
}
print(Add(1,2))

Sum <- function(...)
{
	oParams = list(...)
	vSum <- 0
	for (vValue in oParams)
		vSum <- vSum + vValue
	return (vSum)
}

[Ruby]

def Add(vNum1, vNum2)
	return vNum1 + vNum2
end

def Sum(*oParams)
	vSum = 0
	for vValue in oParams
		vSum += vValue
	end
	return vSum
end

[Rust]

fn Add(vNum1: i32, vNum2: i32) -> i32
{
	return vNum1 + vNum2;
}

//using the alternative 'return' syntax:
//'The final expression in the function will be used as [the] return value.'
fn AddAlt(vNum1: i32, vNum2: i32) -> i32
{
	vNum1 + vNum2
}

//WARNING: Rust doesn't have variadic functions, so accept a vector instead:
fn Sum(oVec: Vec<i32>) -> i32
{
	let mut vSum = 0;
	for vValue in oVec
	{
		vSum += vValue
	}
	return vSum;
}

[Swift]

func Add(_ vNum1: Int, _ vNum2: Int) -> Int
{
	return vNum1 + vNum2
}

func Sum(_ oParams: Int...) -> Int
{
	var vSum = 0
	for vValue in oParams
	{
		vSum += vValue
	}
	return vSum
}

Section: Assign/Declare Single Variables UFL: VarDecl [declare a variable, without assigning a value] AutoHotkey: ___ [e.g. (within a function): local a] C++: int a; C#: int a; Crystal: a: Int32 Excel: ___ Excel VBA: Dim a As Integer Go: Java: int a; JavaScript: var a; Kotlin: var a: Int PHP: ___ Python: ___ R: Ruby: ___ Rust: let mut a: i32; Swift: var a: Int UFL: VarDeclSetAuto [assign variable (infer type)] AutoHotkey: vText := "abc" C++: auto vText = "abc" C#: var vText = "abc" Crystal: vText = "abc" Excel: ___ Excel VBA: vText = "abc" Go: Java: var vText = "abc" JavaScript: vText = "abc" Kotlin: var vText = "abc" PHP: $vText = "abc" Python: vText = "abc" R: Ruby: vText = "abc" Rust: let vText = "abc" [also: let mut vText = "abc"] Swift: var vText = "abc" UFL: VarDeclSet [assign variable (specify type)][or specify type hints/type annotations] AutoHotkey: ___ C++: std::string vText = "abc" C#: string vText = "abc" [note: 'String' also works] Crystal: vText: String = "abc" Excel: ___ Excel VBA: ___ [note: declaration/assignment keywords: Dim/ReDim/Set] Go: Java: String vText = "abc" JavaScript: ___ Kotlin: var vText: String = "abc" PHP: ___ Python: vText: str = "abc" R: Ruby: ___ Rust: let mut vText: String = "abc".to_string() [e.g. let vNum: i32 = 123] Swift: var vText: String = "abc" UFL: VarSet [assign a variable (update value)] AutoHotkey: a := 1 C++: a = 1; C#: a = 1; Crystal: a = 1 Excel: ___ Excel VBA: a = 1 Go: Java: a = 1; JavaScript: a = 1; Kotlin: a = 1 PHP: $a = 1; Python: a = 1 R: Ruby: a = 1 Rust: a = 1; Swift: a = 1 Section: Assign/Declare Multiple Variables UFL: VarDeclMult [declare multiple variables, without assigning values] AutoHotkey: ___ [e.g. (within a function): local a, b, c] C++: int a, b, c; C#: int a, b, c; Crystal: a: Int32; b: Int32; c: Int32 Excel: ___ Excel VBA: Dim a, b, c As Integer Go: Java: int a, b, c; JavaScript: var a, b, c; Kotlin: var a:Int; var b:Int; var c:Int PHP: ___ Python: ___ R: Ruby: ___ Rust: let (mut a, mut b, mut c): (i32, i32, i32); Swift: var a, b, c: Int UFL: VarDeclSetMult [declare and assign multiple variables] AutoHotkey: ___ [e.g. (within a function): local a:=1, b:=2, c:=3] C++: int a=1, b=2, c=3; C#: int a=1, b=2, c=3; [also (destructuring assignment): var (a, b, c) = (1, 2, 3);] Crystal: a: Int32 = 1; b: Int32 = 2; c: Int32 = 3 Excel: ___ Excel VBA: ___ Go: Java: int a=1, b=2, c=3; JavaScript: var a=1, b=2, c=3; [also (destructuring assignment): var [a, b, c] = [1, 2, 3];] Kotlin: var a=1; var b=2; var c=3 [also: var a:Int=1; var b:Int=2; var c:Int=3][also (destructuring assignment) (destructuring declaration): var (a, b, c) = arrayOf(1, 2, 3)][also: var (a:Int, b:Int, c:Int) = arrayOf(1, 2, 3)] PHP: ___ Python: ___ R: Ruby: ___ Rust: let (mut a, mut b, mut c): (i32, i32, i32) = (1, 2, 3); Swift: var a=1, b=2, c=3 [also: var a:Int=1, b:Int=2, c:Int=3][also (destructuring assignment): var (a, b, c) = (1, 2, 3)] UFL: VarSetMult [assign multiple variables] AutoHotkey: a:=1, b:=2, c:=3 C++: a=1; b=2; c=3; [also: a=1, b=2, c=3;] C#: a=1; b=2; c=3; [also (destructuring assignment): (a, b, c) = (1, 2, 3);] Crystal: a=1; b=2; c=3 [also (destructuring assignment): a, b, c = 1, 2, 3] Excel: ___ Excel VBA: a = 1: b = 2: c = 3 Go: Java: a=1; b=2; c=3; JavaScript: a=1; b=2; c=3; [also: a=1, b=2, c=3;][also (destructuring assignment): [a, b, c] = [1, 2, 3];] Kotlin: a=1; b=2; c=3 PHP: $a=1; $b=2; $c=3; [also (destructuring assignment): [$a, $b, $c] = [1, 2, 3];] Python: a=1; b=2; c=3 [also (destructuring assignment): a, b, c = 1, 2, 3] R: Ruby: a=1; b=2; c=3 [also (destructuring assignment): a, b, c = 1, 2, 3] Rust: a=1; b=2; c=3; [also (destructuring assignment): (a, b, c) = (1, 2, 3);] Swift: a=1; b=2; c=3 [also (destructuring assignment): (a, b, c) = (1, 2, 3)] UFL: VarDeclSetMultSame [declare and assign multiple variables, to the same value] AutoHotkey: ___ [WARNING (only creates static variable 'a'): static a := b := c := 123] C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: Java: ___ JavaScript: var a = b = c = 123; [also (destructuring assignment): var [a, b, c] = Array(3).fill(123);] Kotlin: var (a, b, c) = IntArray(3){123} [also: var (a, b, c) = (123, 123, 123)][note (both): destructuring assignment (destructuring declaration)][also: var (a:Int, b:Int, c:Int) = IntArray(3){123}][also: var (a:Int, b:Int, c:Int) = arrayOf(123, 123, 123)] PHP: ___ Python: ___ R: Ruby: ___ Rust: let [mut a, mut b, mut c] = [123; 3]; [note: destructuring assignment] Swift: var (a, b, c) = (123, 123, 123) UFL: VarSetMultSame [assign multiple variables, to the same value] AutoHotkey: a := b := c := 123 C++: a = b = c = 123; C#: a = b = c = 123; Crystal: a = b = c = 123 [also (destructuring assignment): a, b, c = Array.new(3, 123)] Excel: ___ Excel VBA: ___ Go: Java: a = b = c = 123; JavaScript: a = b = c = 123; [also (destructuring assignment): [a, b, c] = Array(3).fill(123);] Kotlin: ___ [note: can do destructuring declaration, but not destructuring assignment] PHP: $a = $b = $c = 123; [also (destructuring assignment): [$a, $b, $c] = array_fill(0, 3, 123);] Python: a = b = c = 123 [also (destructuring assignment): a, b, c = [123] * 3] R: Ruby: a = b = c = 123 [also (destructuring assignment): a, b, c = Array.new(3, 123)] Rust: [a, b, c] = [123; 3]; [note: destructuring assignment] Swift: (a, b, c) = (123, 123, 123) Section: Multi-Line Strings

UFL: StrMultiLine [multi-line strings][WARNING: some approaches crop whitespace (e.g. all whitespace, e.g. some whitespace based on indentation)]

C: concatenate operator
J: join method/function
X: other

[AutoHotkey]

vTextC1 := "Line 1`n"
. "Line 2`n"
. "Line 3"

vTextC2 := "Line 1`n" .
"Line 2`n" .
"Line 3"

vTextX1 := " ;continuation section
(
Line 1
Line 2
Line 3
)"

vTextX2 := " ;continuation section
(Join`r`n
Line 1
Line 2
Line 3
)"

MsgBox(vTextC1)
MsgBox(vTextC2)
MsgBox(vTextX1)
MsgBox(vTextX2)

[C++]

//doesn't work:
//std::string vTextC1 = "LINE 1\n"
//+ "LINE 2\n"
//+ "LINE 3";

//doesn't work:
//std::string vTextC2 = "LINE 1\n" +
//"LINE 2\n" +
//"LINE 3";

//string literal concatenation (no operators needed):
std::string vTextC1 = "LINE 1\n"
"LINE 2\n"
"LINE 3";

std::string vTextX1 = "LINE 1\n\
LINE 2\n\
LINE 3";

std::string vTextX2 = R"(LINE 1
LINE 2
LINE 3)";

std::cout << vTextC1 << "\n";
std::cout << vTextX1 << "\n";
std::cout << vTextX2 << "\n";

[C#]

string vTextC1 = "LINE 1\n"
+ "LINE 2\n"
+ "LINE 3";

string vTextC2 = "LINE 1\n" +
"LINE 2\n" +
"LINE 3";

string vTextJ1 = String.Join("\n"
, "LINE 1"
, "LINE 2"
, "LINE 3"
);

string vTextJ2 = String.Join("\n",
"LINE 1",
"LINE 2",
"LINE 3"
);

string vTextX1 = @"LINE 1
LINE 2
LINE 3";

Console.WriteLine(vTextC1);
Console.WriteLine(vTextC2);
Console.WriteLine(vTextJ1);
Console.WriteLine(vTextJ2);
Console.WriteLine(vTextX1);

[Crystal]

vTextC1 = "LINE 1\n" +
"LINE 2\n" +
"LINE 3"

vTextJ1 = [
"LINE 1",
"LINE 2",
"LINE 3"
].join("\n")

vTextX1 = "LINE 1
LINE 2
LINE 3"

vTextX2 = "LINE 1\n\
LINE 2\n\
LINE 3"

vTextX3 = "LINE 1\n" \
"LINE 2\n" \
"LINE 3"

vTextX4 = <<-MYTEXT
LINE 1
LINE 2
LINE 3
MYTEXT

vTextX5 = %q(LINE 1
LINE 2
LINE 3
)

puts vTextC1
puts vTextJ1
puts vTextX1
puts vTextX2
puts vTextX3
puts vTextX4
puts vTextX5

[Excel]

[Excel VBA]

vTextC1 = "LINE 1" & vbLf & _
"LINE 2" & vbLf & _
"LINE 3"

vTextC2 = "LINE 1" & vbLf _
& "LINE 2" & vbLf _
& "LINE 3"

Debug.Print vTextC1
Debug.Print vTextC2

[Go]

	//WARNING: Golang online compiler auto-indents code:
	//WARNING: Golang online compiler sometimes enforces a space after the comment symbol ('//'):

	vTextC1 := "LINE 1\n" +
		"LINE 2\n" +
		"LINE 3"

	vTextJ1 := strings.Join([]string{"LINE 1",
		"LINE 2",
		"LINE 3"},
		"\n")

	//WARNING: preserves leading whitespace:
	vTextX1 := `LINE 1
LINE 2
LINE 3
`

	fmt.Println(vTextC1)
	fmt.Println(vTextJ1)
	fmt.Println(vTextX1)

[Java]

String vTextC1 = "LINE 1\n"
+ "LINE 2\n"
+ "LINE 3";

String vTextC2 = "LINE 1\n" +
"LINE 2\n" +
"LINE 3";

String vTextJ1 = String.join("\n"
, "LINE 1"
, "LINE 2"
, "LINE 3"
);

String vTextJ2 = String.join("\n",
"LINE 1",
"LINE 2",
"LINE 3"
);

String vTextX1 = """
LINE 1
LINE 2
LINE 3""";

System.out.println(vTextC1);
System.out.println(vTextC2);
System.out.println(vTextJ1);
System.out.println(vTextJ2);
System.out.println(vTextX1);

[JavaScript]

vTextC1 = "LINE 1\n"
+ "LINE 2\n"
+ "LINE 3";

vTextC2 = "LINE 1\n" +
"LINE 2\n" +
"LINE 3";

vTextJ1 = ["LINE 1"
, "LINE 2"
, "LINE 3"
].join("\n")

vTextJ2 = [
"LINE 1",
"LINE 2",
"LINE 3"
].join("\n")

vTextX1 = "LINE 1\n\
LINE 2\n\
LINE 3";

vTextX2 = `LINE 1
LINE 2
LINE 3`;

console.log(vTextC1);
console.log(vTextC2);
console.log(vTextJ1);
console.log(vTextJ2);
console.log(vTextX1);
console.log(vTextX2);

[Kotlin]

//doesn't work:
//vTextC1 = "LINE 1\n"
//+ "LINE 2\n"
//+ "LINE 3"

var vTextC1 = ("LINE 1\n"
+ "LINE 2\n"
+ "LINE 3")

var vTextC2 = "LINE 1\n" +
"LINE 2\n" +
"LINE 3"

var vTextJ1 = arrayOf("LINE 1"
, "LINE 2"
, "LINE 3"
).joinToString("\n")

var vTextJ2 = arrayOf(
"LINE 1",
"LINE 2",
"LINE 3"
).joinToString("\n")

var vTextX1 = """LINE 1
LINE 2
LINE 3"""

println(vTextC1)
println(vTextC2)
println(vTextJ1)
println(vTextJ2)
println(vTextX1)

[PHP]

$vTextC1 = "LINE 1\n"
. "LINE 2\n"
. "LINE 3";

$vTextC2 = "LINE 1\n" .
"LINE 2\n" .
"LINE 3";

$vTextJ1 = implode("\n", ["LINE 1"
, "LINE 2"
, "LINE 3"
]);

$vTextJ2 = implode("\n", [
"LINE 1",
"LINE 2",
"LINE 3"
]);

$vTextX1 = "LINE 1
LINE 2
LINE 3";
$vTextX1 = str_replace("\r", "", $vTextX1);

//e.g. Nowdoc string:
$vTextX2 = <<<'END'
LINE 1
LINE 2
LINE 3
END;

echo $vTextC1 . "\n";
echo $vTextC2 . "\n";
echo $vTextJ1 . "\n";
echo $vTextJ2 . "\n";
echo $vTextX1 . "\n";
echo $vTextX2 . "\n";

[Python]

#doesn't work:
#vTextC1 = "LINE 1\n"
#+ "LINE 2\n"
#+ "LINE 3"

#doesn't work:
#vTextC2 = "LINE 1\n" +
#"LINE 2\n" +
#"LINE 3"

vTextC1 = ("LINE 1\n"
+ "LINE 2\n"
+ "LINE 3")

vTextC2 = ("LINE 1\n" +
"LINE 2\n" +
"LINE 3")

vTextJ1 = "\n".join(["LINE 1"
, "LINE 2"
, "LINE 3"
])

vTextJ2 = "\n".join([
"LINE 1",
"LINE 2",
"LINE 3"
])

vTextX1 = "LINE 1\n" \
+ "LINE 2\n" \
+ "LINE 3"

vTextX2 = """LINE 1
LINE 2
LINE 3"""

print(vTextC1)
print(vTextC2)
print(vTextJ1)
print(vTextJ2)
print(vTextX1)
print(vTextX2)

[R]

vTextJ1 = paste("LINE 1"
, "LINE 2"
, "LINE 3"
, sep="\n")

vTextJ2 = paste("LINE 1",
"LINE 2",
"LINE 3",
sep="\n")

vTextX1 = "LINE 1
LINE 2
LINE 3"

cat(vTextJ1); cat("\n")
cat(vTextJ2); cat("\n")
cat(vTextX1); cat("\n")

[Ruby]

vTextC1 = "LINE 1\n" +
"LINE 2\n" +
"LINE 3"

vTextJ1 = [
"LINE 1",
"LINE 2",
"LINE 3"
].join("\n")

vTextX1 = "LINE 1
LINE 2
LINE 3"

vTextX2 = "LINE 1\n\
LINE 2\n\
LINE 3"

vTextX3 = "LINE 1\n" \
"LINE 2\n" \
"LINE 3"

vTextX4 = <<-MYTEXT
LINE 1
LINE 2
LINE 3
MYTEXT

vTextX5 = <<~MYTEXT
LINE 1
LINE 2
LINE 3
MYTEXT

vTextX6 = %q(LINE 1
LINE 2
LINE 3
)

puts vTextC1
puts vTextJ1
puts vTextX1
puts vTextX2
puts vTextX3
puts vTextX4
puts vTextX5
puts vTextX6

[Rust]

let vTextX1 = "LINE 1
LINE 2
LINE 3";

let vTextX2 = "LINE 1\n\
LINE 2\n\
LINE 3";

let vTextX3 = concat!("LINE 1\n"
, "LINE 2\n"
, "LINE 3"
);

println!("{}", vTextX1);
println!("{}", vTextX2);
println!("{}", vTextX3);

[Swift]

var vTextC1 = "LINE 1\n"
+ "LINE 2\n"
+ "LINE 3"

var vTextC2 = "LINE 1\n" +
"LINE 2\n" +
"LINE 3"

var vTextJ1 = ["LINE 1"
, "LINE 2"
, "LINE 3"
].joined(separator:"\n")

var vTextJ2 = [
"LINE 1",
"LINE 2",
"LINE 3"
].joined(separator:"\n")

var vTextX1 = """
LINE 1
LINE 2
LINE 3
"""

print(vTextC1)
print(vTextC2)
print(vTextJ1)
print(vTextJ2)
print(vTextX1)

Section: File Extensions

UFL: FileExtension [file extension] AutoHotkey: ahk C++: cpp [also: c/cxx/cc][also (header files): h/hpp/hxx/hh] C#: cs Crystal: cr Excel: xlsx [also (older Excel versions): xls] Excel VBA: xlsm [also (older Excel versions): xls] Go: go Java: java JavaScript: js [also (related extensions): htm/html/css] Kotlin: kt PHP: php Python: py R: r Ruby: rb Rust: rs Swift: swift Section: Sleep/Tick Counts (benchmark tests)

UFL: BenchmarkTest [benchmark test][sleep and compare tick counts]

[AutoHotkey]

vTick1 := A_TickCount
Sleep(123)
vTick2 := A_TickCount
vDurationMSec := vTick2 - vTick1
MsgBox(vDurationMSec . " msec")

[C++]

#include <iostream>
#include <chrono>
#include <thread>

auto vTick1 = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(123));
auto vTick2 = std::chrono::high_resolution_clock::now();
auto vDurationMSec = std::chrono::duration_cast<std::chrono::milliseconds>(vTick2-vTick1).count();
std::cout << std::to_string(vDurationMSec) + " msec" << "\n";

[C#]

var vTick1 = DateTime.Now;
System.Threading.Thread.Sleep(123);
var vTick2 = DateTime.Now;
var vDurationMSec = (vTick2-vTick1).TotalMilliseconds;
Console.WriteLine(vDurationMSec + " msec");

[Crystal]

oTick1 = Time.monotonic
sleep 123/1000
oTick2 = Time.monotonic
vDurationMSec = (oTick2-oTick1).total_milliseconds
puts vDurationMSec.to_s + " msec"

[Excel]

[Excel VBA]

#If VBA7 Then
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

vTick1 = Timer
'Application.Wait (Now + TimeValue("0:00:01"))
Sleep (123) 'Winapi function kernel32\Sleep, more accurate than Application.Wait
vTick2 = Timer
vDurationMSec = Int((vTick2 - vTick1) * 1000)
Debug.Print (vDurationMSec & " msec")

[Go]

//requires: import "time" abd "strconv"

oTime1 := time.Now()
time.Sleep(123 * time.Millisecond)
oTime2 := time.Now()
vDurationMSec := oTime2.Sub(oTime1).Milliseconds()
fmt.Println(strconv.Itoa(int(vDurationMSec)) + " msec")

[Java]

var vTick1 = System.currentTimeMillis();
try
{
	Thread.sleep(123);
}
catch (Exception e)
{
}
var vTick2 = System.currentTimeMillis();
var vDurationMSec = vTick2 - vTick1;
System.out.println(vDurationMSec + " msec");

[JavaScript]

vTick1 = performance.now();
var vDate = 123 + new Date().getTime();
while (new Date() < vDate)
	{} //noop
vTick2 = performance.now();
vDurationMSec = vTick2 - vTick1;
console.log(vDurationMSec + " msec");

[Kotlin]

var vTick1 = System.currentTimeMillis()
Thread.sleep(123)
var vTick2 = System.currentTimeMillis()
var vDurationMSec = vTick2 - vTick1
println("" + vDurationMSec + " msec")

[PHP]

$vTick1 = microtime(true);
usleep(123*1000); //note: usleep uses microseconds (1000 microseconds = 1 millisecond)
$vTick2 = microtime(true);
$vDurationMSec = intval(($vTick2-$vTick1)*1000);
var_export($vDurationMSec . " msec");

[Python]

import time

vTick1 = time.time()
time.sleep(123/1000)
vTick2 = time.time()
vDurationMSec = int((vTick2-vTick1)*1000)
print(str(vDurationMSec) + " msec")

[R]

oTime1 <- Sys.time()
Sys.sleep(123/1000)
oTime2 <- Sys.time()
vDurationMSec = as.numeric(oTime2-oTime1) * 1000
print(sprintf("%0.4f msec", vDurationMSec))
#print(paste(vDurationMSec, "msec")) #for more decimal places

[Ruby]

oTick1 = Time.now
sleep 123/1000.0
oTick2 = Time.now
vDurationMSec = (oTick2-oTick1) * 1000
puts vDurationMSec.to_s + " msec"

[Rust]

use std::{thread, time};

let oDate1 = time::SystemTime::now();
thread::sleep(time::Duration::from_millis(123));
let oDate2 = time::SystemTime::now();
let vDurationMSec = oDate2.duration_since(oDate1).unwrap().as_millis();
println!("{}{}", vDurationMSec, " msec");

[Swift]

import Foundation

var oTick1 = DispatchTime.now()
usleep(123*1000)
var oTick2 = DispatchTime.now()
var vDurationNSec = oTick2.uptimeNanoseconds - oTick1.uptimeNanoseconds
var vDurationMSec = vDurationNSec / 1000000
print(String(vDurationMSec) + " msec")

Section: Concatenate Strings/Integers UFL: StrIntConcat [can concatenate string and int directly?] AutoHotkey: yes [e.g. vText . vNum][e.g. vNum . vText][e.g. vText vNum][e.g. vNum vText] C++: no [can use: vText + std::to_string(vNum)][can use: std::to_string(vNum) + vText] C#: yes [e.g. vText + vNum][e.g. vNum + vText] Crystal: no [can use: vText + vNum.to_s][also: vNum.to_s + vText] Excel: yes [e.g. =A1&B1][=B1&A1] Excel VBA: yes [e.g. vText & vNum][e.g. vNum & vText] Go: Java: yes [e.g. vText + vNum][e.g. vNum + vText] JavaScript: yes [e.g. vText + vNum][e.g. vNum + vText] Kotlin: depends on order [e.g. vText + vNum][can use: "" + vNum + vText] PHP: yes [e.g. $vText . $vNum][e.g. $vNum . $vText] Python: no [can use: vText + str(vNum)][also: str(vNum) + vText] R: Ruby: no [can use: vText + vNum.to_s][also: vNum.to_s + vText] Rust: no [can use: format!("{}{}", vText, vNum)][can use: format!("{}{}", vNum, vText)] Swift: no [can use: vText + String(vNum)][can use: String(vNum) + vText] The Universal Function Library Project: Details Note: UFL: Universal Function Library, a set of around 100-300 standard functions for all programming languages. UFL notes: Tern ['c ? x : y' is preferable since it's clear/concise/common, else use alternative symbols like Raku ('c ?? x !! y')][a ternary function is a lesser option since it can't do short-circuit Boolean evaluation] recommendation: 'c ? x : y' is extremely clear and concise and very well known, if you create a programming language, you should implement it just like that, and if your programming language for whatever failed to do that (and even if has some alternative syntax ...), choose alternative symbols (e.g. Raku: 'c ?? x !! y') author's note: unlike with 'c ? x : y', where either x or y are not executed, depending on c, for the function 'Tern(c, x, y)', x and y will both be executed) UFL notes: Swap [consider 'Swap(&a, &b)' or 'Swap(a, b)' or a swap statement 'swap a b'][destructuring assignment is unclear when longer variable names are used] author's note: (all of the options aside from 'Swap(&a, &b)' and 'swap a b' are poor) author's note: a function is a fine option, if the language supports functions with ByRef variables: 'Swap(&a, &b)' (or possibly 'Swap(a, b)') author's note: 'swap a b' is a good option for any programming language author's note: 't = a, a = b, b = t', is verbose (e.g. a 3-liner, plus blank lines, plus a comment to say 'swap', plus longer variable names), can easily result in bugs (especially when code is updated and variables are renamed), and it doesn't make the intention clear, a user can't simply search 'swap' to find any swaps in the code author's note: destructuring assignment only looks clear when the variable name ares are unusually short author's note: if all languages implemented 'swap a b' or 'Swap(&a, &b)', this would make it easy to migrate code between programming languages, otherwise simply swapping variables will be a recurring headache author's note: there are huge numbers of views on Stack Overflow etc, on threads re. swapping variables author's note: the only argument against a swap statement/function, is that swapping is relatively uncommon, however, it is relatively verbose, and relatively unsafe author's note: in general, well-known operations should be doable at the level the user thinks of them ('I'm swapping variables a and b', not, 'I'm creating a temporary variable and using it to swap a and b') author's note: in general, well-known operations should be doable in as safe a way as possible, having to name each variable twice, and name a temporary variable twice, and 3 assignments where something may be ordered incorrectly, are chances for more bugs, and reasonably often exactly these bugs do occur author's note: many approaches have the side effect of introducing a temporary variable author's note: oArray.Swap(Key1, Key2) and oMap.Swap(Key1, Key2) are also useful, add a swap statement/function, and then you can easily find variable and object key swaps by searching for 'swap' author's note: a swap statement/function is easier to find, understand and debug than the alternatives author's note: if it can be written badly, it will be written badly, a swap statement/function is very hard to get wrong UFL notes: Sleep [perhaps consider friendly format options e.g. 'm'/'s'] UFL notes: Noop recommendation: the string 'noop' is uncommon, so it is easier to search for than 'nop' and 'pass', which are relatively common substrings of words recommendation: either a noop statement or function is fine recommendation: a noop statement, that can't be overridden, may be useful as it enables the language to be sure it can replace the statement with a noop, no other checks are required recommendation: people use makeshift noops, a built-in noop, makes it easier to find any noops, for later removal recommendation: noops are useful as a line for adding breakpoints recommendation: some versions of noops can be confusing, e.g. '{}', because the programmer must remember not to add a trailing semicolon UFL notes: PrintLn [print string and a newline character] recommendation: a 'PrintLn' that always appends a line break, is more useful than a 'Print' that doesn't, if only one can be picked recommendation: since 'Print' with line break is wanted 99%+ of the time, it is fine for 'Print' to print a line break by default, with an option or separate function to print without a line break UFL notes: TickCount [get the current time in milliseconds (typically centisecond accuracy, or a higher resolution if possible), take the difference of 2 timestamps to get the time elapsed] UFL notes: SetTimer recommendation: it may be worth having 3 options: delay before first occurrence, gap in-between occurrences, number of occurrences UFL notes: Type UFL notes: Error UFL notes: Assert recommendation: it may be worth having variants of this function, e.g. assert that an error would occur if it were run, e.g. instead of 1 param that is a bool, perhaps 2 params (actual value, expected value), perhaps 3 params (function, parameters as an array, expected value)