authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-01-10 19:31:28-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-01-10 19:31:45-07:00
logaba8d4f62c5643333ca50a884c0fa1898a31dfed
treed8eb251d21368aebe0d7bb5012fe4e163218fb74
parent45ec85173329a62bef54a51603b366771ad89281

langref: document inline functions


1 files changed, 38 insertions(+), 0 deletions(-)

doc/langref.html.in+38
...@@ -5370,6 +5370,44 @@ test "fn type inference" {...@@ -5370,6 +5370,44 @@ test "fn type inference" {
5370 {#code_end#}5370 {#code_end#}
53715371
5372 {#header_close#}5372 {#header_close#}
5373
5374 {#header_open|inline fn#}
5375 <p>
5376 Adding the {#syntax#}inline{#endsyntax#} keyword to a function definition makes that
5377 function become <em>semantically inlined</em> at the callsite. This is
5378 not a hint to be possibly observed by optimization passes, but has
5379 implications on the types and values involved in the function call.
5380 </p>
5381 <p>
5382 Unlike normal function calls, arguments at an inline function callsite which are
5383 compile-time known are treated as {#link|Compile Time Parameters#}. This can potentially
5384 propagate all the way to the return value:
5385 </p>
5386 {#code_begin|test|inline_call#}
5387test "inline function call" {
5388 if (foo(1200, 34) != 1234) {
5389 @compileError("bad");
5390 }
5391}
5392
5393inline fn foo(a: i32, b: i32) i32 {
5394 return a + b;
5395}
5396 {#code_end#}
5397 <p>If {#syntax#}inline{#endsyntax#} is removed, the test fails with the compile error
5398 instead of passing.</p>
5399 <p>It is generally better to let the compiler decide when to inline a
5400 function, except for these scenarios:</p>
5401 <ul>
5402 <li>To change how many stack frames are in the call stack, for debugging purposes.</li>
5403 <li>To force comptime-ness of the arguments to propagate to the return value of the function, as in the above example.</i>
5404 <li>Real world performance measurements demand it.</li>
5405 </ul>
5406 <p>Note that {#syntax#}inline{#endsyntax#} actually <em>restricts</em>
5407 what the compiler is allowed to do. This can harm binary size,
5408 compilation speed, and even runtime performance.</p>
5409 {#header_close#}
5410
5373 {#header_open|Function Reflection#}5411 {#header_open|Function Reflection#}
5374 {#code_begin|test|test_fn_reflection#}5412 {#code_begin|test|test_fn_reflection#}
5375const std = @import("std");5413const std = @import("std");