1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documentation - The Zig Programming Language</title>
<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAgklEQVR4AWMYWuD7EllJIM4G4g4g5oIJ/odhOJ8wToOxSTXgNxDHoeiBMfA4+wGShjyYOCkG/IGqWQziEzYAoUAeiF9D5U+DxEg14DRU7jWIT5IBIOdCxf+A+CQZAAoopEB7QJwBCBwHiip8UYmRdrAlDpIMgApwQZNnNii5Dq0MBgCxxycBnwEd+wAAAABJRU5ErkJggg==">
<style>
:root{
--nav-width: 24em;
--nav-margin-l: 1em;
}
body{
font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif;
margin: 0;
line-height: 1.5;
}
header {
padding: 0 1em;
}
#contents {
max-width: 60em;
margin: auto;
padding: 0 1em;
}
#navigation {
padding: 0 1em;
}
@media screen and (min-width: 1025px) {
header {
margin-left: calc(var(--nav-width) + var(--nav-margin-l));
}
header h1 {
margin: auto;
max-width: 30em;
}
#navigation {
overflow: auto;
width: var(--nav-width);
height: 100vh;
position: fixed;
top:0;
left:0;
bottom:0;
padding: unset;
margin-left: var(--nav-margin-l);
}
#navigation nav ul {
padding-left: 1em;
}
#contents-wrapper {
margin-left: calc(var(--nav-width) + var(--nav-margin-l));
}
}
a:hover,a:focus {
background: #fff2a8;
}
dt {
font-weight: bold;
}
table, th, td {
border-collapse: collapse;
border: 1px solid grey;
}
th, td {
padding: 0.1em;
}
th[scope=row] {
text-align: left;
font-weight: normal;
}
.t0_1, .t37, .t37_1 {
font-weight: bold;
}
.t2_0 {
color: #575757;
}
.t31_1 {
color: #b40000;
}
.t32_1 {
color: green;
}
.t36_1 {
color: #005C7A;
}
.file {
font-weight: bold;
border: unset;
}
code {
background: #f8f8f8;
border: 1px dotted silver;
padding-left: 0.3em;
padding-right: 0.3em;
}
pre > code {
display: block;
overflow: auto;
padding: 0.5em;
border: 1px solid #eee;
line-height: normal;
}
samp {
background: #fafafa;
}
pre > samp {
display: block;
overflow: auto;
padding: 0.5em;
border: 1px solid #eee;
line-height: normal;
}
kbd {
font-weight: bold;
}
.table-wrapper {
width: 100%;
overflow-x: auto;
}
.tok-kw {
color: #333;
font-weight: bold;
}
.tok-str {
color: #d14;
}
.tok-builtin {
color: #005C7A;
}
.tok-comment {
color: #545454;
font-style: italic;
}
.tok-fn {
color: #900;
font-weight: bold;
}
.tok-null {
color: #005C5C;
}
.tok-number {
color: #005C5C;
}
.tok-type {
color: #458;
font-weight: bold;
}
figure {
margin: auto 0;
}
figure pre {
margin-top: 0;
}
figcaption {
padding-left: 0.5em;
font-size: small;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
figcaption.zig-cap {
background: #fcdba5;
}
figcaption.c-cap {
background: #a8b9cc;
color: #000;
}
figcaption.peg-cap {
background: #fcdba5;
}
figcaption.javascript-cap {
background: #365d95;
color: #fff;
}
figcaption.shell-cap {
background: #ccc;
color: #000;
}
aside {
border-left: 0.25em solid #f7a41d;
padding: 0 1em 0 1em;
}
h1 a, h2 a, h3 a, h4 a, h5 a {
text-decoration: none;
color: #333;
}
a.hdr {
visibility: hidden;
}
h1:hover > a.hdr, h2:hover > a.hdr, h3:hover > a.hdr, h4:hover > a.hdr, h5:hover > a.hdr {
visibility: visible;
}
pre {
counter-reset: line;
}
pre .line:before {
counter-increment: line;
content: counter(line);
display: inline-block;
padding-right: 1em;
width: 2em;
text-align: right;
color: #999;
}
th pre code {
background: none;
}
th .line:before {
display: none;
}
@media (prefers-color-scheme: dark) {
body{
background:#121212;
color: #ccc;
}
a {
color: #88f;
}
a:hover,a:focus {
color: #000;
}
table, th, td {
border-color: grey;
}
.t2_0 {
color: grey;
}
.t31_1 {
color: red;
}
.t32_1 {
color: #00B800;
}
.t36_1 {
color: #0086b3;
}
code {
background: #222;
border-color: #444;
}
pre > code {
color: #ccc;
background: #222;
border: unset;
}
samp {
background: #000;
color: #ccc;
}
pre > samp {
border: unset;
}
.tok-kw {
color: #eee;
}
.tok-str {
color: #2e5;
}
.tok-builtin {
color: #ff894c;
}
.tok-comment {
color: #aa7;
}
.tok-fn {
color: #B1A0F8;
}
.tok-null {
color: #ff8080;
}
.tok-number {
color: #ff8080;
}
.tok-type {
color: #68f;
}
h1 a, h2 a, h3 a, h4 a, h5 a {
color: #aaa;
}
figcaption.zig-cap {
background-color: #b27306;
color: #000;
}
figcaption.peg-cap {
background-color: #b27306;
color: #000;
}
figcaption.shell-cap {
background: #2a2a2a;
color: #fff;
}
}
@media all {
main {
counter-reset: section-2;
}
h2 {
counter-reset: section-3;
}
h2::before {
counter-increment: section-2;
content: counter(section-2) ". ";
font-weight: normal;
}
h3 {
counter-reset: section-4;
}
h3::before {
counter-increment: section-3;
content: counter(section-2) "." counter(section-3) ". ";
font-weight: normal;
}
h4::before {
counter-increment: section-4;
content: counter(section-2) "." counter(section-3) "." counter(section-4) ". ";
font-weight: normal;
}
#zig-version::before {
content: "";
}
#table-of-contents::before {
content: "";
}
}
</style>
</head>
<body>
<header><h1>Zig Language Reference</h1></header>
<div id="main-wrapper">
<div id="navigation">
<nav aria-labelledby="zig-version">
<h2 id="zig-version">Zig Version</h2>
<a href="https://ziglang.org/documentation/0.1.1/">0.1.1</a> |
<a href="https://ziglang.org/documentation/0.2.0/">0.2.0</a> |
<a href="https://ziglang.org/documentation/0.3.0/">0.3.0</a> |
<a href="https://ziglang.org/documentation/0.4.0/">0.4.0</a> |
<a href="https://ziglang.org/documentation/0.5.0/">0.5.0</a> |
<a href="https://ziglang.org/documentation/0.6.0/">0.6.0</a> |
<a href="https://ziglang.org/documentation/0.7.1/">0.7.1</a> |
<a href="https://ziglang.org/documentation/0.8.1/">0.8.1</a> |
<a href="https://ziglang.org/documentation/0.9.1/">0.9.1</a> |
<a href="https://ziglang.org/documentation/0.10.1/">0.10.1</a> |
master
</nav>
<nav aria-labelledby="table-of-contents">
<h2 id="table-of-contents">Table of Contents</h2>
{#nav#}
</nav>
</div>
<div id="contents-wrapper"><main id="contents">
{#header_open|Introduction#}
<p>
<a href="https://ziglang.org">Zig</a> is a general-purpose programming language and toolchain for maintaining
<strong>robust</strong>, <strong>optimal</strong>, and <strong>reusable</strong> software.
</p>
<dl>
<dt>Robust</dt><dd>Behavior is correct even for edge cases such as out of memory.</dd>
<dt>Optimal</dt><dd>Write programs the best way they can behave and perform.</dd>
<dt>Reusable</dt><dd>The same code works in many environments which have different
constraints.</dd>
<dt>Maintainable</dt><dd>Precisely communicate intent to the compiler and
other programmers. The language imposes a low overhead to reading code and is
resilient to changing requirements and environments.</dd>
</dl>
<p>
Often the most efficient way to learn something new is to see examples, so
this documentation shows how to use each of Zig's features. It is
all on one page so you can search with your browser's search tool.
</p>
<p>
The code samples in this document are compiled and tested as part of the main test suite of Zig.
</p>
<p>
This HTML document depends on no external files, so you can use it offline.
</p>
{#header_close#}
{#header_open|Zig Standard Library#}
<p>
The <a href="https://ziglang.org/documentation/master/std/">Zig Standard Library</a> has its own documentation.
</p>
<p>
Zig's Standard Library contains commonly used algorithms, data structures, and definitions to help you build programs or libraries.
You will see many examples of Zig's Standard Library used in this documentation. To learn more about the Zig Standard Library,
visit the link above.
</p>
{#header_close#}
{#header_open|Hello World#}
{#code_begin|exe|hello#}
const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello, {s}!\n", .{"world"});
}
{#code_end#}
<p>
The Zig code sample above demonstrates one way to create a program that will output: <samp>Hello, world!</samp>.
</p>
<p>
The code sample shows the contents of a file named <code class="file">hello.zig</code>. Files storing Zig
source code are {#link|UTF-8 encoded|Source Encoding#} text files. The files storing
Zig source code are usually named with the <code class="file"><em>.zig</em></code> extension.
</p>
<p>
Following the <code class="file">hello.zig</code> Zig code sample, the {#link|Zig Build System#} is used
to build an executable program from the <code class="file">hello.zig</code> source code. Then, the
<code class="file">hello</code> program is executed showing its output <samp>Hello, world!</samp>. The
lines beginning with <samp>$</samp> represent command line prompts and a command.
Everything else is program output.
</p>
<p>
The code sample begins by adding the {#link|Zig Standard Library#} to the build using the {#link|@import#} builtin function.
The {#syntax#}@import("std"){#endsyntax#} function call creates a structure that represents the Zig Standard Library.
The code then {#link|declares|Container Level Variables#} a
{#link|constant identifier|Assignment#}, named {#syntax#}std{#endsyntax#}, that gives access to the features of the Zig Standard Library.
</p>
<p>
Next, a {#link|public function|Functions#}, {#syntax#}pub fn{#endsyntax#}, named {#syntax#}main{#endsyntax#}
is declared. The {#syntax#}main{#endsyntax#} function is necessary because it tells the Zig compiler where the start of
the program exists. Programs designed to be executed will need a {#syntax#}pub fn main{#endsyntax#} function.
</p>
<aside role="note" aria-label="Note about main function">
<p>
For more advanced use cases, Zig offers other features to inform the compiler where the start of
the program exists. Also, libraries do not need a {#syntax#}pub fn main{#endsyntax#} function because
library code is called by other programs or libraries.
</p>
</aside>
<p>
A function is a block of any number of statements and expressions that, as a whole, perform a task.
Functions may or may not return data after they are done performing their task. If a function
cannot perform its task, it might return an error. Zig makes all of this explicit.
</p>
<p>
In the <code class="file">hello.zig</code> code sample, the <code>main</code> function is declared
with the {#syntax#}!void{#endsyntax#} return type. This return type is known as an {#link|Error Union Type#}.
This syntax tells the Zig compiler that the function will either return an
error or a value. An error union type combines an {#link|Error Set Type#} and any other data type
(e.g. a {#link|Primitive Type|Primitive Types#} or a user-defined type such as a {#link|struct#}, {#link|enum#}, or {#link|union#}).
The full form of an error union type is
<code><error set type></code>{#syntax#}!{#endsyntax#}<code><any data type></code>. In the code
sample, the error set type is not explicitly written on the left side of the {#syntax#}!{#endsyntax#} operator.
When written this way, the error set type is an {#link|inferred error set type|Inferred Error Sets#}. The
{#syntax#}void{#endsyntax#} after the {#syntax#}!{#endsyntax#} operator
tells the compiler that the function will not return a value under normal circumstances (i.e. when no errors occur).
</p>
<aside role="note" aria-label="Note to disambiguate exclamation mark operator">
<p>
Note to experienced programmers: Zig also has the boolean {#link|operator|Operators#} {#syntax#}!a{#endsyntax#}
where {#syntax#}a{#endsyntax#} is a value of type {#syntax#}bool{#endsyntax#}. Error union types contain the
name of the type in the syntax: {#syntax#}!{#endsyntax#}<code><any data type></code>.
</p>
</aside>
<p>
In Zig, a function's block of statements and expressions are surrounded by an open curly-brace <code>{</code> and
close curly-brace <code>}</code>. Inside of the {#syntax#}main{#endsyntax#} function are expressions that perform
the task of outputting <samp>Hello, world!</samp> to standard output.
</p>
<p>
First, a constant identifier, {#syntax#}stdout{#endsyntax#}, is initialized to represent standard output's
writer. Then, the program tries to print the <samp>Hello, world!</samp>
message to standard output.
</p>
<p>
Functions sometimes need information to perform their task. In Zig, information is passed
to functions between an open parenthesis {#syntax#}({#endsyntax#} and a close parenthesis {#syntax#}){#endsyntax#} placed after
the function's name. This information is also known as arguments. When there are
multiple arguments passed to a function, they are separated by commas {#syntax#},{#endsyntax#}.
</p>
<p>
The two arguments passed to the {#syntax#}stdout.print(){#endsyntax#} function, {#syntax#}"Hello, {s}!\n"{#endsyntax#}
and {#syntax#}.{"world"}{#endsyntax#}, are evaluated at {#link|compile-time|comptime#}. The code sample is
purposely written to show how to perform {#link|string|String Literals and Unicode Code Point Literals#}
substitution in the {#syntax#}print{#endsyntax#} function. The curly-braces inside of the first argument
are substituted with the compile-time known value inside of the second argument
(known as an {#link|tuple|Tuples#}). The <code>\n</code>
inside of the double-quotes of the first argument is the {#link|escape sequence|Escape Sequences#} for the
newline character. The {#link|try#} expression evaluates the result of {#syntax#}stdout.print{#endsyntax#}.
If the result is an error, then the {#syntax#}try{#endsyntax#} expression will return from
{#syntax#}main{#endsyntax#} with the error. Otherwise, the program will continue. In this case, there are no
more statements or expressions left to execute in the {#syntax#}main{#endsyntax#} function, so the program exits.
</p>
<p>
In Zig, the standard output writer's {#syntax#}print{#endsyntax#} function is allowed to fail because
it is actually a function defined as part of a generic Writer. Consider a generic Writer that
represents writing data to a file. When the disk is full, a write to the file will fail.
However, we typically do not expect writing text to the standard output to fail. To avoid having
to handle the failure case of printing to standard output, you can use alternate functions: the
functions in {#syntax#}std.log{#endsyntax#} for proper logging or the {#syntax#}std.debug.print{#endsyntax#} function.
This documentation will use the latter option to print to standard error (stderr) and silently return
on failure. The next code sample, <code class="file">hello_again.zig</code> demonstrates the use of
{#syntax#}std.debug.print{#endsyntax#}.
</p>
{#code_begin|exe|hello_again#}
const print = @import("std").debug.print;
pub fn main() void {
print("Hello, world!\n", .{});
}
{#code_end#}
<p>
Note that you can leave off the {#syntax#}!{#endsyntax#} from the return type because {#syntax#}std.debug.print{#endsyntax#} cannot fail.
</p>
{#see_also|Values|@import|Errors|Root Source File|Source Encoding#}
{#header_close#}
{#header_open|Comments#}
{#code_begin|exe|comments#}
const print = @import("std").debug.print;
pub fn main() void {
// Comments in Zig start with "//" and end at the next LF byte (end of line).
// The line below is a comment and won't be executed.
//print("Hello?", .{});
print("Hello, world!\n", .{}); // another comment
}
{#code_end#}
<p>
There are no multiline comments in Zig (e.g. like <code class="c">/* */</code>
comments in C). This helps allow Zig to have the property that each line
of code can be tokenized out of context.
</p>
{#header_open|Doc comments#}
<p>
A doc comment is one that begins with exactly three slashes (i.e.
{#syntax#}///{#endsyntax#} but not {#syntax#}////{#endsyntax#});
multiple doc comments in a row are merged together to form a multiline
doc comment. The doc comment documents whatever immediately follows it.
</p>
{#code_begin|syntax|doc_comments#}
/// A structure for storing a timestamp, with nanosecond precision (this is a
/// multiline doc comment).
const Timestamp = struct {
/// The number of seconds since the epoch (this is also a doc comment).
seconds: i64, // signed so we can represent pre-1970 (not a doc comment)
/// The number of nanoseconds past the second (doc comment again).
nanos: u32,
/// Returns a `Timestamp` struct representing the Unix epoch; that is, the
/// moment of 1970 Jan 1 00:00:00 UTC (this is a doc comment too).
pub fn unixEpoch() Timestamp {
return Timestamp{
.seconds = 0,
.nanos = 0,
};
}
};
{#code_end#}
<p>
Doc comments are only allowed in certain places; eventually, it will
become a compile error to have a doc comment in an unexpected place, such as
in the middle of an expression, or just before a non-doc comment.
</p>
{#header_close#}
{#header_open|Top-Level Doc Comments#}
<p>User documentation that doesn't belong to whatever
immediately follows it, like {#link|container|Containers#}-level documentation, goes
in top-level doc comments. A top-level doc comment is one that
begins with two slashes and an exclamation point:
{#syntax#}//!{#endsyntax#}.</p>
{#code_begin|syntax|tldoc_comments#}
//! This module provides functions for retrieving the current date and
//! time with varying degrees of precision and accuracy. It does not
//! depend on libc, but will use functions from it if available.
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Values#}
{#code_begin|exe|values#}
// Top-level declarations are order-independent:
const print = std.debug.print;
const std = @import("std");
const os = std.os;
const assert = std.debug.assert;
pub fn main() void {
// integers
const one_plus_one: i32 = 1 + 1;
print("1 + 1 = {}\n", .{one_plus_one});
// floats
const seven_div_three: f32 = 7.0 / 3.0;
print("7.0 / 3.0 = {}\n", .{seven_div_three});
// boolean
print("{}\n{}\n{}\n", .{
true and false,
true or false,
!true,
});
// optional
var optional_value: ?[]const u8 = null;
assert(optional_value == null);
print("\noptional 1\ntype: {}\nvalue: {?s}\n", .{
@TypeOf(optional_value), optional_value,
});
optional_value = "hi";
assert(optional_value != null);
print("\noptional 2\ntype: {}\nvalue: {?s}\n", .{
@TypeOf(optional_value), optional_value,
});
// error union
var number_or_error: anyerror!i32 = error.ArgNotFound;
print("\nerror union 1\ntype: {}\nvalue: {!}\n", .{
@TypeOf(number_or_error), number_or_error, });
number_or_error = 1234;
print("\nerror union 2\ntype: {}\nvalue: {!}\n", .{
@TypeOf(number_or_error), number_or_error,
});
}
{#code_end#}
{#header_open|Primitive Types#}
<div class="table-wrapper">
<table>
<caption>Primitive Types</caption>
<thead>
<tr>
<th scope="col">Type</th>
<th scope="col">C Equivalent</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">{#syntax#}i8{#endsyntax#}</th>
<td><code class="c">int8_t</code></td>
<td>signed 8-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}u8{#endsyntax#}</th>
<td><code class="c">uint8_t</code></td>
<td>unsigned 8-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}i16{#endsyntax#}</th>
<td><code class="c">int16_t</code></td>
<td>signed 16-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}u16{#endsyntax#}</th>
<td><code class="c">uint16_t</code></td>
<td>unsigned 16-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}i32{#endsyntax#}</th>
<td><code class="c">int32_t</code></td>
<td>signed 32-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}u32{#endsyntax#}</th>
<td><code class="c">uint32_t</code></td>
<td>unsigned 32-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}i64{#endsyntax#}</th>
<td><code class="c">int64_t</code></td>
<td>signed 64-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}u64{#endsyntax#}</th>
<td><code class="c">uint64_t</code></td>
<td>unsigned 64-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}i128{#endsyntax#}</th>
<td><code class="c">__int128</code></td>
<td>signed 128-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}u128{#endsyntax#}</th>
<td><code class="c">unsigned __int128</code></td>
<td>unsigned 128-bit integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}isize{#endsyntax#}</th>
<td><code class="c">intptr_t</code></td>
<td>signed pointer sized integer</td>
</tr>
<tr>
<th scope="row">{#syntax#}usize{#endsyntax#}</th>
<td><code class="c">uintptr_t</code>, <code class="c">size_t</code></td>
<td>unsigned pointer sized integer. Also see <a href="https://github.com/ziglang/zig/issues/5185">#5185</a></td>
</tr>
<tr>
<th scope="row">{#syntax#}c_short{#endsyntax#}</th>
<td><code class="c">short</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_ushort{#endsyntax#}</th>
<td><code class="c">unsigned short</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_int{#endsyntax#}</th>
<td><code class="c">int</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_uint{#endsyntax#}</th>
<td><code class="c">unsigned int</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_long{#endsyntax#}</th>
<td><code class="c">long</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_ulong{#endsyntax#}</th>
<td><code class="c">unsigned long</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_longlong{#endsyntax#}</th>
<td><code class="c">long long</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_ulonglong{#endsyntax#}</th>
<td><code class="c">unsigned long long</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}c_longdouble{#endsyntax#}</th>
<td><code class="c">long double</code></td>
<td>for ABI compatibility with C</td>
</tr>
<tr>
<th scope="row">{#syntax#}f16{#endsyntax#}</th>
<td><code class="c">_Float16</code></td>
<td>16-bit floating point (10-bit mantissa) IEEE-754-2008 binary16</td>
</tr>
<tr>
<th scope="row">{#syntax#}f32{#endsyntax#}</th>
<td><code class="c">float</code></td>
<td>32-bit floating point (23-bit mantissa) IEEE-754-2008 binary32</td>
</tr>
<tr>
<th scope="row">{#syntax#}f64{#endsyntax#}</th>
<td><code class="c">double</code></td>
<td>64-bit floating point (52-bit mantissa) IEEE-754-2008 binary64</td>
</tr>
<tr>
<th scope="row">{#syntax#}f80{#endsyntax#}</th>
<td><code class="c">double</code></td>
<td>80-bit floating point (64-bit mantissa) IEEE-754-2008 80-bit extended precision</td>
</tr>
<tr>
<th scope="row">{#syntax#}f128{#endsyntax#}</th>
<td><code class="c">_Float128</code></td>
<td>128-bit floating point (112-bit mantissa) IEEE-754-2008 binary128</td>
</tr>
<tr>
<th scope="row">{#syntax#}bool{#endsyntax#}</th>
<td><code class="c">bool</code></td>
<td>{#syntax#}true{#endsyntax#} or {#syntax#}false{#endsyntax#}</td>
</tr>
<tr>
<th scope="row">{#syntax#}anyopaque{#endsyntax#}</th>
<td><code class="c">void</code></td>
<td>Used for type-erased pointers.</td>
</tr>
<tr>
<th scope="row">{#syntax#}void{#endsyntax#}</th>
<td>(none)</td>
<td>Always the value {#syntax#}void{}{#endsyntax#}</td>
</tr>
<tr>
<th scope="row">{#syntax#}noreturn{#endsyntax#}</th>
<td>(none)</td>
<td>the type of {#syntax#}break{#endsyntax#}, {#syntax#}continue{#endsyntax#}, {#syntax#}return{#endsyntax#}, {#syntax#}unreachable{#endsyntax#}, and {#syntax#}while (true) {}{#endsyntax#}</td>
</tr>
<tr>
<th scope="row">{#syntax#}type{#endsyntax#}</th>
<td>(none)</td>
<td>the type of types</td>
</tr>
<tr>
<th scope="row">{#syntax#}anyerror{#endsyntax#}</th>
<td>(none)</td>
<td>an error code</td>
</tr>
<tr>
<th scope="row">{#syntax#}comptime_int{#endsyntax#}</th>
<td>(none)</td>
<td>Only allowed for {#link|comptime#}-known values. The type of integer literals.</td>
</tr>
<tr>
<th scope="row">{#syntax#}comptime_float{#endsyntax#}</th>
<td>(none)</td>
<td>Only allowed for {#link|comptime#}-known values. The type of float literals.</td>
</tr>
</tbody>
</table>
</div>
<p>
In addition to the integer types above, arbitrary bit-width integers can be referenced by using
an identifier of <code>i</code> or <code>u</code> followed by digits. For example, the identifier
{#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an
integer type is {#syntax#}65535{#endsyntax#}.
</p>
{#see_also|Integers|Floats|void|Errors|@Type#}
{#header_close#}
{#header_open|Primitive Values#}
<div class="table-wrapper">
<table>
<caption>Primitive Values</caption>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">{#syntax#}true{#endsyntax#} and {#syntax#}false{#endsyntax#}</th>
<td>{#syntax#}bool{#endsyntax#} values</td>
</tr>
<tr>
<th scope="row">{#syntax#}null{#endsyntax#}</th>
<td>used to set an optional type to {#syntax#}null{#endsyntax#}</td>
</tr>
<tr>
<th scope="row">{#syntax#}undefined{#endsyntax#}</th>
<td>used to leave a value unspecified</td>
</tr>
</tbody>
</table>
</div>
{#see_also|Optionals|undefined#}
{#header_close#}
{#header_open|String Literals and Unicode Code Point Literals#}
<p>
String literals are constant single-item {#link|Pointers#} to null-terminated byte arrays.
The type of string literals encodes both the length, and the fact that they are null-terminated,
and thus they can be {#link|coerced|Type Coercion#} to both {#link|Slices#} and
{#link|Null-Terminated Pointers|Sentinel-Terminated Pointers#}.
Dereferencing string literals converts them to {#link|Arrays#}.
</p>
<p>
The encoding of a string in Zig is de-facto assumed to be UTF-8.
Because Zig source code is {#link|UTF-8 encoded|Source Encoding#}, any non-ASCII bytes appearing within a string literal
in source code carry their UTF-8 meaning into the content of the string in the Zig program;
the bytes are not modified by the compiler.
However, it is possible to embed non-UTF-8 bytes into a string literal using <code>\xNN</code> notation.
</p>
<p>
Unicode code point literals have type {#syntax#}comptime_int{#endsyntax#}, the same as
{#link|Integer Literals#}. All {#link|Escape Sequences#} are valid in both string literals
and Unicode code point literals.
</p>
<p>
In many other programming languages, a Unicode code point literal is called a "character literal".
However, there is <a href="https://unicode.org/glossary">no precise technical definition of a "character"</a>
in recent versions of the Unicode specification (as of Unicode 13.0).
In Zig, a Unicode code point literal corresponds to the Unicode definition of a code point.
</p>
{#code_begin|exe|string_literals#}
const print = @import("std").debug.print;
const mem = @import("std").mem; // will be used to compare bytes
pub fn main() void {
const bytes = "hello";
print("{}\n", .{@TypeOf(bytes)}); // *const [5:0]u8
print("{d}\n", .{bytes.len}); // 5
print("{c}\n", .{bytes[1]}); // 'e'
print("{d}\n", .{bytes[5]}); // 0
print("{}\n", .{'e' == '\x65'}); // true
print("{d}\n", .{'\u{1f4a9}'}); // 128169
print("{d}\n", .{'💯'}); // 128175
print("{}\n", .{mem.eql(u8, "hello", "h\x65llo")}); // true
print("0x{x}\n", .{"\xff"[0]}); // non-UTF-8 strings are possible with \xNN notation.
print("{u}\n", .{'⚡'});
}
{#code_end#}
{#see_also|Arrays|Source Encoding#}
{#header_open|Escape Sequences#}
<div class="table-wrapper">
<table>
<caption>Escape Sequences</caption>
<thead>
<tr>
<th scope="col">Escape Sequence</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"><code>\n</code></th>
<td>Newline</td>
</tr>
<tr>
<th scope="row"><code>\r</code></th>
<td>Carriage Return</td>
</tr>
<tr>
<th scope="row"><code>\t</code></th>
<td>Tab</td>
</tr>
<tr>
<th scope="row"><code>\\</code></th>
<td>Backslash</td>
</tr>
<tr>
<th scope="row"><code>\'</code></th>
<td>Single Quote</td>
</tr>
<tr>
<th scope="row"><code>\"</code></th>
<td>Double Quote</td>
</tr>
<tr>
<th scope="row"><code>\xNN</code></th>
<td>hexadecimal 8-bit byte value (2 digits)</td>
</tr>
<tr>
<th scope="row"><code>\u{NNNNNN}</code></th>
<td>hexadecimal Unicode code point UTF-8 encoded (1 or more digits)</td>
</tr>
</tbody>
</table>
</div>
<p>Note that the maximum valid Unicode point is {#syntax#}0x10ffff{#endsyntax#}.</p>
{#header_close#}
{#header_open|Multiline String Literals#}
<p>
Multiline string literals have no escapes and can span across multiple lines.
To start a multiline string literal, use the {#syntax#}\\{#endsyntax#} token. Just like a comment,
the string literal goes until the end of the line. The end of the line is
not included in the string literal.
However, if the next line begins with {#syntax#}\\{#endsyntax#} then a newline is appended and
the string literal continues.
</p>
{#code_begin|syntax|multiline_string_literals#}
const hello_world_in_c =
\\#include <stdio.h>
\\
\\int main(int argc, char **argv) {
\\ printf("hello world\n");
\\ return 0;
\\}
;
{#code_end#}
{#see_also|@embedFile#}
{#header_close#}
{#header_close#}
{#header_open|Assignment#}
<p>Use the {#syntax#}const{#endsyntax#} keyword to assign a value to an identifier:</p>
{#code_begin|exe_build_err|constant_identifier_cannot_change#}
const x = 1234;
fn foo() void {
// It works at file scope as well as inside functions.
const y = 5678;
// Once assigned, an identifier cannot be changed.
y += 1;
}
pub fn main() void {
foo();
}
{#code_end#}
<p>{#syntax#}const{#endsyntax#} applies to all of the bytes that the identifier immediately addresses. {#link|Pointers#} have their own const-ness.</p>
<p>If you need a variable that you can modify, use the {#syntax#}var{#endsyntax#} keyword:</p>
{#code_begin|exe|mutable_var#}
const print = @import("std").debug.print;
pub fn main() void {
var y: i32 = 5678;
y += 1;
print("{d}", .{y});
}
{#code_end#}
<p>Variables must be initialized:</p>
{#code_begin|exe_build_err|var_must_be_initialized#}
pub fn main() void {
var x: i32;
x = 1;
}
{#code_end#}
{#header_open|undefined#}
<p>Use {#syntax#}undefined{#endsyntax#} to leave variables uninitialized:</p>
{#code_begin|exe|assign_undefined#}
const print = @import("std").debug.print;
pub fn main() void {
var x: i32 = undefined;
x = 1;
print("{d}", .{x});
}
{#code_end#}
<p>
{#syntax#}undefined{#endsyntax#} can be {#link|coerced|Type Coercion#} to any type.
Once this happens, it is no longer possible to detect that the value is {#syntax#}undefined{#endsyntax#}.
{#syntax#}undefined{#endsyntax#} means the value could be anything, even something that is nonsense
according to the type. Translated into English, {#syntax#}undefined{#endsyntax#} means "Not a meaningful
value. Using this value would be a bug. The value will be unused, or overwritten before being used."
</p>
<p>
In {#link|Debug#} mode, Zig writes {#syntax#}0xaa{#endsyntax#} bytes to undefined memory. This is to catch
bugs early, and to help detect use of undefined memory in a debugger. However, this behavior is only an
implementation feature, not a language semantic, so it is not guaranteed to be observable to code.
</p>
{#header_close#}
{#header_close#}
{#header_close#}
{#header_open|Zig Test#}
<p>
Code written within one or more {#syntax#}test{#endsyntax#} declarations can be used to ensure behavior meets expectations:
</p>
{#code_begin|test|testing_introduction#}
const std = @import("std");
test "expect addOne adds one to 41" {
// The Standard Library contains useful functions to help create tests.
// `expect` is a function that verifies its argument is true.
// It will return an error if its argument is false to indicate a failure.
// `try` is used to return an error to the test runner to notify it that the test failed.
try std.testing.expect(addOne(41) == 42);
}
/// The function `addOne` adds one to the number given as its argument.
fn addOne(number: i32) i32 {
return number + 1;
}
{#code_end#}
<p>
The <code class="file">introducing_zig_test.zig</code> code sample tests the {#link|function|Functions#}
{#syntax#}addOne{#endsyntax#} to ensure that it returns {#syntax#}42{#endsyntax#} given the input
{#syntax#}41{#endsyntax#}. From this test's perspective, the {#syntax#}addOne{#endsyntax#} function is
said to be <em>code under test</em>.
</p>
<p>
<kbd>zig test</kbd> is a tool that creates and runs a test build. By default, it builds and runs an
executable program using the <em>default test runner</em> provided by the {#link|Zig Standard Library#}
as its main entry point. During the build, {#syntax#}test{#endsyntax#} declarations found while
{#link|resolving|Root Source File#} the given Zig source file are included for the default test runner
to run and report on.
</p>
<aside>
This documentation discusses the features of the default test runner as provided by the Zig Standard Library.
Its source code is located in <code class="file">lib/test_runner.zig</code>.
</aside>
<p>
The shell output shown above displays two lines after the <kbd>zig test</kbd> command. These lines are
printed to standard error by the default test runner:
</p>
<dl>
<dt><samp>Test [1/1] test "expect addOne adds one to 41"...</samp></dt>
<dd>Lines like this indicate which test, out of the total number of tests, is being run.
In this case, <samp>[1/1]</samp> indicates that the first test, out of a total of
one test, is being run. Note that, when the test runner program's standard error is output
to the terminal, these lines are cleared when a test succeeds.
</dd>
<dt><samp>All 1 tests passed.</samp></dt>
<dd>This line indicates the total number of tests that have passed.</dd>
</dl>
{#header_open|Test Declarations#}
<p>
Test declarations contain the {#link|keyword|Keyword Reference#} {#syntax#}test{#endsyntax#}, followed by an
optional name written as a {#link|string literal|String Literals and Unicode Code Point Literals#}, followed
by a {#link|block|Blocks#} containing any valid Zig code that is allowed in a {#link|function|Functions#}.
</p>
<aside>
By convention, non-named tests should only be used to {#link|make other tests run|Nested Container Tests#}.
Non-named tests cannot be {#link|filtered|Skip Tests#}.
</aside>
<p>
Test declarations are similar to {#link|Functions#}: they have a return type and a block of code. The implicit
return type of {#syntax#}test{#endsyntax#} is the {#link|Error Union Type#} {#syntax#}anyerror!void{#endsyntax#},
and it cannot be changed. When a Zig source file is not built using the <kbd>zig test</kbd> tool, the test
declarations are omitted from the build.
</p>
<p>
Test declarations can be written in the same file, where code under test is written, or in a separate Zig source file.
Since test declarations are top-level declarations, they are order-independent and can
be written before or after the code under test.
</p>
{#see_also|The Global Error Set|Grammar#}
{#header_close#}
{#header_open|Nested Container Tests#}
<p>
When the <kbd>zig test</kbd> tool is building a test runner, only resolved {#syntax#}test{#endsyntax#}
declarations are included in the build. Initially, only the given Zig source file's top-level
declarations are resolved. Unless nested {#link|containers|Containers#} are referenced from a top-level test declaration,
nested container tests will not be resolved.
</p>
<p>
The code sample below uses the {#syntax#}std.testing.refAllDecls(@This()){#endsyntax#} function call to
reference all of the containers that are in the file including the imported Zig source file. The code
sample also shows an alternative way to reference containers using the {#syntax#}_ = C;{#endsyntax#}
syntax. This syntax tells the compiler to ignore the result of the expression on the right side of the
assignment operator.
</p>
{#code_begin|test|testing_nested_container_tests#}
const std = @import("std");
const expect = std.testing.expect;
// Imported source file tests will run when referenced from a top-level test declaration.
// The next line alone does not cause "introducing_zig_test.zig" tests to run.
const imported_file = @import("testing_introduction.zig");
test {
// To run nested container tests, either, call `refAllDecls` which will
// reference all declarations located in the given argument.
// `@This()` is a builtin function that returns the innermost container it is called from.
// In this example, the innermost container is this file (implicitly a struct).
std.testing.refAllDecls(@This());
// or, reference each container individually from a top-level test declaration.
// The `_ = C;` syntax is a no-op reference to the identifier `C`.
_ = S;
_ = U;
_ = @import("testing_introduction.zig");
}
const S = struct {
test "S demo test" {
try expect(true);
}
const SE = enum {
V,
// This test won't run because its container (SE) is not referenced.
test "This Test Won't Run" {
try expect(false);
}
};
};
const U = union { // U is referenced by the file's top-level test declaration
s: US, // and US is referenced here; therefore, "U.Us demo test" will run
const US = struct {
test "U.US demo test" {
// This test is a top-level test declaration for the struct.
// The struct is nested (declared) inside of a union.
try expect(true);
}
};
test "U demo test" {
try expect(true);
}
};
{#code_end#}
{#header_close#}
{#header_open|Test Failure#}
<p>
The default test runner checks for an {#link|error|Errors#} returned from a test.
When a test returns an error, the test is considered a failure and its {#link|error return trace|Error Return Traces#}
is output to standard error. The total number of failures will be reported after all tests have run.
</p>
{#code_begin|test_err|testing_failure#}
const std = @import("std");
test "expect this to fail" {
try std.testing.expect(false);
}
test "expect this to succeed" {
try std.testing.expect(true);
}
{#code_end#}
{#header_close#}
{#header_open|Skip Tests#}
<p>
One way to skip tests is to filter them out by using the <kbd>zig test</kbd> command line parameter
<kbd>--test-filter [text]</kbd>. This makes the test build only include tests whose name contains the
supplied filter text. Note that non-named tests are run even when using the <kbd>--test-filter [text]</kbd>
command line parameter.
</p>
<p>
To programmatically skip a test, make a {#syntax#}test{#endsyntax#} return the error
{#syntax#}error.SkipZigTest{#endsyntax#} and the default test runner will consider the test as being skipped.
The total number of skipped tests will be reported after all tests have run.
</p>
{#code_begin|test|testing_skip#}
test "this will be skipped" {
return error.SkipZigTest;
}
{#code_end#}
{#header_close#}
{#header_open|Report Memory Leaks#}
<p>
When code allocates {#link|Memory#} using the {#link|Zig Standard Library#}'s testing allocator,
{#syntax#}std.testing.allocator{#endsyntax#}, the default test runner will report any leaks that are
found from using the testing allocator:
</p>
{#code_begin|test_err|testing_detect_leak|1 tests leaked memory#}
const std = @import("std");
test "detect leak" {
var list = std.ArrayList(u21).init(std.testing.allocator);
// missing `defer list.deinit();`
try list.append('☔');
try std.testing.expect(list.items.len == 1);
}
{#code_end#}
{#see_also|defer|Memory#}
{#header_close#}
{#header_open|Detecting Test Build#}
<p>
Use the {#link|compile variable|Compile Variables#} {#syntax#}@import("builtin").is_test{#endsyntax#}
to detect a test build:
</p>
{#code_begin|test|testing_detect_test#}
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
test "builtin.is_test" {
try expect(isATest());
}
fn isATest() bool {
return builtin.is_test;
}
{#code_end#}
{#header_close#}
{#header_open|Test Output and Logging#}
<p>
The default test runner and the Zig Standard Library's testing namespace output messages to standard error.
</p>
{#header_close#}
{#header_open|The Testing Namespace#}
<p>
The Zig Standard Library's <code>testing</code> namespace contains useful functions to help
you create tests. In addition to the <code>expect</code> function, this document uses a couple of more functions
as exemplified here:
</p>
{#code_begin|test|testing_namespace#}
const std = @import("std");
test "expectEqual demo" {
const expected: i32 = 42;
const actual = 42;
// The first argument to `expectEqual` is the known, expected, result.
// The second argument is the result of some expression.
// The actual's type is casted to the type of expected.
try std.testing.expectEqual(expected, actual);
}
test "expectError demo" {
const expected_error = error.DemoError;
const actual_error_union: anyerror!void = error.DemoError;
// `expectError` will fail when the actual error is different than
// the expected error.
try std.testing.expectError(expected_error, actual_error_union);
}
{#code_end#}
<p>The Zig Standard Library also contains functions to compare {#link|Slices#}, strings, and more. See the rest of the
{#syntax#}std.testing{#endsyntax#} namespace in the {#link|Zig Standard Library#} for more available functions.</p>
{#header_close#}
{#header_open|Test Tool Documentation#}
<p>
<kbd>zig test</kbd> has a few command line parameters which affect the compilation.
See <kbd>zig test --help</kbd> for a full list.
</p>
{#header_close#}
{#header_close#}
{#header_open|Variables#}
<p>
A variable is a unit of {#link|Memory#} storage.
</p>
<p>
It is generally preferable to use {#syntax#}const{#endsyntax#} rather than
{#syntax#}var{#endsyntax#} when declaring a variable. This causes less work for both
humans and computers to do when reading code, and creates more optimization opportunities.
</p>
{#header_open|Identifiers#}
<p>
Variable identifiers are never allowed to shadow identifiers from an outer scope.
</p>
<p>
Identifiers must start with an alphabetic character or underscore and may be followed
by any number of alphanumeric characters or underscores.
They must not overlap with any keywords. See {#link|Keyword Reference#}.
</p>
<p>
If a name that does not fit these requirements is needed, such as for linking with external libraries, the {#syntax#}@""{#endsyntax#} syntax may be used.
</p>
{#code_begin|syntax|identifiers#}
const @"identifier with spaces in it" = 0xff;
const @"1SmallStep4Man" = 112358;
const c = @import("std").c;
pub extern "c" fn @"error"() void;
pub extern "c" fn @"fstat$INODE64"(fd: c.fd_t, buf: *c.Stat) c_int;
const Color = enum {
red,
@"really red",
};
const color: Color = .@"really red";
{#code_end#}
{#header_close#}
{#header_open|Container Level Variables#}
<p>
{#link|Container|Containers#} level variables have static lifetime and are order-independent and lazily analyzed.
The initialization value of container level variables is implicitly
{#link|comptime#}. If a container level variable is {#syntax#}const{#endsyntax#} then its value is
{#syntax#}comptime{#endsyntax#}-known, otherwise it is runtime-known.
</p>
{#code_begin|test|test_container_level_variables#}
var y: i32 = add(10, x);
const x: i32 = add(12, 34);
test "container level variables" {
try expect(x == 46);
try expect(y == 56);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
const std = @import("std");
const expect = std.testing.expect;
{#code_end#}
<p>
Container level variables may be declared inside a {#link|struct#}, {#link|union#}, {#link|enum#}, or {#link|opaque#}:
</p>
{#code_begin|test|test_namespaced_container_level_variable#}
const std = @import("std");
const expect = std.testing.expect;
test "namespaced container level variable" {
try expect(foo() == 1235);
try expect(foo() == 1236);
}
const S = struct {
var x: i32 = 1234;
};
fn foo() i32 {
S.x += 1;
return S.x;
}
{#code_end#}
{#header_close#}
{#header_open|Static Local Variables#}
<p>
It is also possible to have local variables with static lifetime by using containers inside functions.
</p>
{#code_begin|test|test_static_local_variable#}
const std = @import("std");
const expect = std.testing.expect;
test "static local variable" {
try expect(foo() == 1235);
try expect(foo() == 1236);
}
fn foo() i32 {
const S = struct {
var x: i32 = 1234;
};
S.x += 1;
return S.x;
}
{#code_end#}
<p>
The {#syntax#}extern{#endsyntax#} keyword or {#link|@extern#} builtin function can be used to link against a variable that is exported
from another object. The {#syntax#}export{#endsyntax#} keyword or {#link|@export#} builtin function
can be used to make a variable available to other objects at link time. In both cases,
the type of the variable must be C ABI compatible.
</p>
{#see_also|Exporting a C Library#}
{#header_close#}
{#header_open|Thread Local Variables#}
<p>A variable may be specified to be a thread-local variable using the
{#syntax#}threadlocal{#endsyntax#} keyword:</p>
{#code_begin|test|test_thread_local_variables#}
const std = @import("std");
const assert = std.debug.assert;
threadlocal var x: i32 = 1234;
test "thread local storage" {
const thread1 = try std.Thread.spawn(.{}, testTls, .{});
const thread2 = try std.Thread.spawn(.{}, testTls, .{});
testTls();
thread1.join();
thread2.join();
}
fn testTls() void {
assert(x == 1234);
x += 1;
assert(x == 1235);
}
{#code_end#}
<p>
For {#link|Single Threaded Builds#}, all thread local variables are treated as regular {#link|Container Level Variables#}.
</p>
<p>
Thread local variables may not be {#syntax#}const{#endsyntax#}.
</p>
{#header_close#}
{#header_open|Local Variables#}
<p>
Local variables occur inside {#link|Functions#}, {#link|comptime#} blocks, and {#link|@cImport#} blocks.
</p>
<p>
When a local variable is {#syntax#}const{#endsyntax#}, it means that after initialization, the variable's
value will not change. If the initialization value of a {#syntax#}const{#endsyntax#} variable is
{#link|comptime#}-known, then the variable is also {#syntax#}comptime{#endsyntax#}-known.
</p>
<p>
A local variable may be qualified with the {#syntax#}comptime{#endsyntax#} keyword. This causes
the variable's value to be {#syntax#}comptime{#endsyntax#}-known, and all loads and stores of the
variable to happen during semantic analysis of the program, rather than at runtime.
All variables declared in a {#syntax#}comptime{#endsyntax#} expression are implicitly
{#syntax#}comptime{#endsyntax#} variables.
</p>
{#code_begin|test|test_comptime_variables#}
const std = @import("std");
const expect = std.testing.expect;
test "comptime vars" {
var x: i32 = 1;
comptime var y: i32 = 1;
x += 1;
y += 1;
try expect(x == 2);
try expect(y == 2);
if (y != 2) {
// This compile error never triggers because y is a comptime variable,
// and so `y != 2` is a comptime value, and this if is statically evaluated.
@compileError("wrong y value");
}
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Integers#}
{#header_open|Integer Literals#}
{#code_begin|syntax|integer_literals#}
const decimal_int = 98222;
const hex_int = 0xff;
const another_hex_int = 0xFF;
const octal_int = 0o755;
const binary_int = 0b11110000;
// underscores may be placed between two digits as a visual separator
const one_billion = 1_000_000_000;
const binary_mask = 0b1_1111_1111;
const permissions = 0o7_5_5;
const big_address = 0xFF80_0000_0000_0000;
{#code_end#}
{#header_close#}
{#header_open|Runtime Integer Values#}
<p>
Integer literals have no size limitation, and if any undefined behavior occurs,
the compiler catches it.
</p>
<p>
However, once an integer value is no longer known at compile-time, it must have a
known size, and is vulnerable to undefined behavior.
</p>
{#code_begin|syntax|runtime_vs_comptime#}
fn divide(a: i32, b: i32) i32 {
return a / b;
}
{#code_end#}
<p>
In this function, values {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are known only at runtime,
and thus this division operation is vulnerable to both {#link|Integer Overflow#} and
{#link|Division by Zero#}.
</p>
<p>
Operators such as {#syntax#}+{#endsyntax#} and {#syntax#}-{#endsyntax#} cause undefined behavior on
integer overflow. Alternative operators are provided for wrapping and saturating arithmetic on all targets.
{#syntax#}+%{#endsyntax#} and {#syntax#}-%{#endsyntax#} perform wrapping arithmetic
while {#syntax#}+|{#endsyntax#} and {#syntax#}-|{#endsyntax#} perform saturating arithmetic.
</p>
<p>
Zig supports arbitrary bit-width integers, referenced by using
an identifier of <code>i</code> or <code>u</code> followed by digits. For example, the identifier
{#syntax#}i7{#endsyntax#} refers to a signed 7-bit integer. The maximum allowed bit-width of an
integer type is {#syntax#}65535{#endsyntax#}. For signed integer types, Zig uses a
<a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement</a> representation.
</p>
{#see_also|Wrapping Operations#}
{#header_close#}
{#header_close#}
{#header_open|Floats#}
<p>Zig has the following floating point types:</p>
<ul>
<li>{#syntax#}f16{#endsyntax#} - IEEE-754-2008 binary16</li>
<li>{#syntax#}f32{#endsyntax#} - IEEE-754-2008 binary32</li>
<li>{#syntax#}f64{#endsyntax#} - IEEE-754-2008 binary64</li>
<li>{#syntax#}f80{#endsyntax#} - IEEE-754-2008 80-bit extended precision</li>
<li>{#syntax#}f128{#endsyntax#} - IEEE-754-2008 binary128</li>
<li>{#syntax#}c_longdouble{#endsyntax#} - matches <code class="c">long double</code> for the target C ABI</li>
</ul>
{#header_open|Float Literals#}
<p>
Float literals have type {#syntax#}comptime_float{#endsyntax#} which is guaranteed to have
the same precision and operations of the largest other floating point type, which is
{#syntax#}f128{#endsyntax#}.
</p>
<p>
Float literals {#link|coerce|Type Coercion#} to any floating point type,
and to any {#link|integer|Integers#} type when there is no fractional component.
</p>
{#code_begin|syntax|float_literals#}
const floating_point = 123.0E+77;
const another_float = 123.0;
const yet_another = 123.0e+77;
const hex_floating_point = 0x103.70p-5;
const another_hex_float = 0x103.70;
const yet_another_hex_float = 0x103.70P-5;
// underscores may be placed between two digits as a visual separator
const lightspeed = 299_792_458.000_000;
const nanosecond = 0.000_000_001;
const more_hex = 0x1234_5678.9ABC_CDEFp-10;
{#code_end#}
<p>
There is no syntax for NaN, infinity, or negative infinity. For these special values,
one must use the standard library:
</p>
{#code_begin|syntax|float_special_values#}
const std = @import("std");
const inf = std.math.inf(f32);
const negative_inf = -std.math.inf(f64);
const nan = std.math.nan(f128);
{#code_end#}
{#header_close#}
{#header_open|Floating Point Operations#}
<p>By default floating point operations use {#syntax#}Strict{#endsyntax#} mode,
but you can switch to {#syntax#}Optimized{#endsyntax#} mode on a per-block basis:</p>
{#code_begin|obj|float_mode_obj#}
{#code_release_fast#}
{#code_disable_cache#}
const std = @import("std");
const big = @as(f64, 1 << 40);
export fn foo_strict(x: f64) f64 {
return x + big - big;
}
export fn foo_optimized(x: f64) f64 {
@setFloatMode(.Optimized);
return x + big - big;
}
{#code_end#}
<p>For this test we have to separate code into two object files -
otherwise the optimizer figures out all the values at compile-time,
which operates in strict mode.</p>
{#code_begin|exe|float_mode_exe#}
{#code_link_object|float_mode_obj#}
const print = @import("std").debug.print;
extern fn foo_strict(x: f64) f64;
extern fn foo_optimized(x: f64) f64;
pub fn main() void {
const x = 0.001;
print("optimized = {}\n", .{foo_optimized(x)});
print("strict = {}\n", .{foo_strict(x)});
}
{#code_end#}
{#see_also|@setFloatMode|Division by Zero#}
{#header_close#}
{#header_close#}
{#header_open|Operators#}
<p>
There is no operator overloading. When you see an operator in Zig, you know that
it is doing something from this table, and nothing else.
</p>
{#header_open|Table of Operators#}
<div class="table-wrapper">
<table>
<caption>Table of Operators</caption>
<thead>
<tr>
<th scope="col">Syntax</th>
<th scope="col">Relevant Types</th>
<th scope="col">Description</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"><pre>{#syntax#}a + b
a += b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>Addition.
<ul>
<li>Can cause {#link|overflow|Default Operations#} for integers.</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
<li>See also {#link|@addWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}2 + 5 == 7{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a +% b
a +%= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Wrapping Addition.
<ul>
<li>Guaranteed to have twos-complement wrapping behavior.</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
<li>See also {#link|@addWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}@as(u32, std.math.maxInt(u32)) +% 1 == 0{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a +| b
a +|= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Saturating Addition.
<ul>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}@as(u32, std.math.maxInt(u32)) +| 1 == @as(u32, std.math.maxInt(u32)){#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a - b
a -= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>Subtraction.
<ul>
<li>Can cause {#link|overflow|Default Operations#} for integers.</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
<li>See also {#link|@subWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}2 - 5 == -3{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a -% b
a -%= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Wrapping Subtraction.
<ul>
<li>Guaranteed to have twos-complement wrapping behavior.</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
<li>See also {#link|@subWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}@as(u32, 0) -% 1 == std.math.maxInt(u32){#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a -| b
a -|= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Saturating Subtraction.
<ul>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}@as(u32, 0) -| 1 == 0{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}-a{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>
Negation.
<ul>
<li>Can cause {#link|overflow|Default Operations#} for integers.</li>
</ul>
</td>
<td>
<pre>{#syntax#}-1 == 0 - 1{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}-%a{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>
Wrapping Negation.
<ul>
<li>Guaranteed to have twos-complement wrapping behavior.</li>
</ul>
</td>
<td>
<pre>{#syntax#}-%@as(i32, std.math.minInt(i32)) == std.math.minInt(i32){#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a * b
a *= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>Multiplication.
<ul>
<li>Can cause {#link|overflow|Default Operations#} for integers.</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
<li>See also {#link|@mulWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}2 * 5 == 10{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a *% b
a *%= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Wrapping Multiplication.
<ul>
<li>Guaranteed to have twos-complement wrapping behavior.</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
<li>See also {#link|@mulWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}@as(u8, 200) *% 2 == 144{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a *| b
a *|= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Saturating Multiplication.
<ul>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}@as(u8, 200) *| 2 == 255{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a / b
a /= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>Division.
<ul>
<li>Can cause {#link|overflow|Default Operations#} for integers.</li>
<li>Can cause {#link|Division by Zero#} for integers.</li>
<li>Can cause {#link|Division by Zero#} for floats in {#link|FloatMode.Optimized Mode|Floating Point Operations#}.</li>
<li>Signed integer operands must be comptime-known and positive. In other cases, use
{#link|@divTrunc#},
{#link|@divFloor#}, or
{#link|@divExact#} instead.
</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}10 / 5 == 2{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a % b
a %= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>Remainder Division.
<ul>
<li>Can cause {#link|Division by Zero#} for integers.</li>
<li>Can cause {#link|Division by Zero#} for floats in {#link|FloatMode.Optimized Mode|Floating Point Operations#}.</li>
<li>Signed or floating-point operands must be comptime-known and positive. In other cases, use
{#link|@rem#} or
{#link|@mod#} instead.
</li>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}10 % 3 == 1{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a << b
a <<= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Bit Shift Left.
<ul>
<li>{#syntax#}b{#endsyntax#} must be {#link|comptime-known|comptime#} or have a type with log2 number of bits as {#syntax#}a{#endsyntax#}.</li>
<li>See also {#link|@shlExact#}.</li>
<li>See also {#link|@shlWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}1 << 8 == 256{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a <<| b
a <<|= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Saturating Bit Shift Left.
<ul>
<li>See also {#link|@shlExact#}.</li>
<li>See also {#link|@shlWithOverflow#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}@as(u8, 1) <<| 8 == 255{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a >> b
a >>= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Bit Shift Right.
<ul>
<li>{#syntax#}b{#endsyntax#} must be {#link|comptime-known|comptime#} or have a type with log2 number of bits as {#syntax#}a{#endsyntax#}.</li>
<li>See also {#link|@shrExact#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}10 >> 1 == 5{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a & b
a &= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Bitwise AND.
<ul>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}0b011 & 0b101 == 0b001{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a | b
a |= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Bitwise OR.
<ul>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}0b010 | 0b100 == 0b110{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a ^ b
a ^= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>Bitwise XOR.
<ul>
<li>Invokes {#link|Peer Type Resolution#} for the operands.</li>
</ul>
</td>
<td>
<pre>{#syntax#}0b011 ^ 0b101 == 0b110{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}~a{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
</ul>
</td>
<td>
Bitwise NOT.
</td>
<td>
<pre>{#syntax#}~@as(u8, 0b10101111) == 0b01010000{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a orelse b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Optionals#}</li>
</ul>
</td>
<td>If {#syntax#}a{#endsyntax#} is {#syntax#}null{#endsyntax#},
returns {#syntax#}b{#endsyntax#} ("default value"),
otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}.
Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}.
</td>
<td>
<pre>{#syntax#}const value: ?u32 = null;
const unwrapped = value orelse 1234;
unwrapped == 1234{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a.?{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Optionals#}</li>
</ul>
</td>
<td>
Equivalent to:
<pre>{#syntax#}a orelse unreachable{#endsyntax#}</pre>
</td>
<td>
<pre>{#syntax#}const value: ?u32 = 5678;
value.? == 5678{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a catch b
a catch |err| b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Error Unions|Errors#}</li>
</ul>
</td>
<td>If {#syntax#}a{#endsyntax#} is an {#syntax#}error{#endsyntax#},
returns {#syntax#}b{#endsyntax#} ("default value"),
otherwise returns the unwrapped value of {#syntax#}a{#endsyntax#}.
Note that {#syntax#}b{#endsyntax#} may be a value of type {#link|noreturn#}.
{#syntax#}err{#endsyntax#} is the {#syntax#}error{#endsyntax#} and is in scope of the expression {#syntax#}b{#endsyntax#}.
</td>
<td>
<pre>{#syntax#}const value: anyerror!u32 = error.Broken;
const unwrapped = value catch 1234;
unwrapped == 1234{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a and b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|bool|Primitive Types#}</li>
</ul>
</td>
<td>
If {#syntax#}a{#endsyntax#} is {#syntax#}false{#endsyntax#}, returns {#syntax#}false{#endsyntax#}
without evaluating {#syntax#}b{#endsyntax#}. Otherwise, returns {#syntax#}b{#endsyntax#}.
</td>
<td>
<pre>{#syntax#}(false and true) == false{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a or b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|bool|Primitive Types#}</li>
</ul>
</td>
<td>
If {#syntax#}a{#endsyntax#} is {#syntax#}true{#endsyntax#}, returns {#syntax#}true{#endsyntax#}
without evaluating {#syntax#}b{#endsyntax#}. Otherwise, returns {#syntax#}b{#endsyntax#}.
</td>
<td>
<pre>{#syntax#}(false or true) == true{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}!a{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|bool|Primitive Types#}</li>
</ul>
</td>
<td>
Boolean NOT.
</td>
<td>
<pre>{#syntax#}!false == true{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a == b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
<li>{#link|bool|Primitive Types#}</li>
<li>{#link|type|Primitive Types#}</li>
</ul>
</td>
<td>
Returns {#syntax#}true{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}false{#endsyntax#}.
Invokes {#link|Peer Type Resolution#} for the operands.
</td>
<td>
<pre>{#syntax#}(1 == 1) == true{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a == null{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Optionals#}</li>
</ul>
</td>
<td>
Returns {#syntax#}true{#endsyntax#} if a is {#syntax#}null{#endsyntax#}, otherwise returns {#syntax#}false{#endsyntax#}.
</td>
<td>
<pre>{#syntax#}const value: ?u32 = null;
value == null{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a != b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
<li>{#link|bool|Primitive Types#}</li>
<li>{#link|type|Primitive Types#}</li>
</ul>
</td>
<td>
Returns {#syntax#}false{#endsyntax#} if a and b are equal, otherwise returns {#syntax#}true{#endsyntax#}.
Invokes {#link|Peer Type Resolution#} for the operands.
</td>
<td>
<pre>{#syntax#}(1 != 1) == false{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a > b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>
Returns {#syntax#}true{#endsyntax#} if a is greater than b, otherwise returns {#syntax#}false{#endsyntax#}.
Invokes {#link|Peer Type Resolution#} for the operands.
</td>
<td>
<pre>{#syntax#}(2 > 1) == true{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a >= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>
Returns {#syntax#}true{#endsyntax#} if a is greater than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}.
Invokes {#link|Peer Type Resolution#} for the operands.
</td>
<td>
<pre>{#syntax#}(2 >= 1) == true{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a < b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>
Returns {#syntax#}true{#endsyntax#} if a is less than b, otherwise returns {#syntax#}false{#endsyntax#}.
Invokes {#link|Peer Type Resolution#} for the operands.
</td>
<td>
<pre>{#syntax#}(1 < 2) == true{#endsyntax#}></pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a <= b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Integers#}</li>
<li>{#link|Floats#}</li>
</ul>
</td>
<td>
Returns {#syntax#}true{#endsyntax#} if a is less than or equal to b, otherwise returns {#syntax#}false{#endsyntax#}.
Invokes {#link|Peer Type Resolution#} for the operands.
</td>
<td>
<pre>{#syntax#}(1 <= 2) == true{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a ++ b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Arrays#}</li>
</ul>
</td>
<td>
Array concatenation.
<ul>
<li>Only available when {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are {#link|compile-time known|comptime#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}const mem = @import("std").mem;
const array1 = [_]u32{1,2};
const array2 = [_]u32{3,4};
const together = array1 ++ array2;
mem.eql(u32, &together, &[_]u32{1,2,3,4}){#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a ** b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Arrays#}</li>
</ul>
</td>
<td>
Array multiplication.
<ul>
<li>Only available when {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#} are {#link|compile-time known|comptime#}.</li>
</ul>
</td>
<td>
<pre>{#syntax#}const mem = @import("std").mem;
const pattern = "ab" ** 3;
mem.eql(u8, pattern, "ababab"){#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a.*{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Pointers#}</li>
</ul>
</td>
<td>
Pointer dereference.
</td>
<td>
<pre>{#syntax#}const x: u32 = 1234;
const ptr = &x;
ptr.* == 1234{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}&a{#endsyntax#}</pre></th>
<td>
All types
</td>
<td>
Address of.
</td>
<td>
<pre>{#syntax#}const x: u32 = 1234;
const ptr = &x;
ptr.* == 1234{#endsyntax#}</pre>
</td>
</tr>
<tr>
<th scope="row"><pre>{#syntax#}a || b{#endsyntax#}</pre></th>
<td>
<ul>
<li>{#link|Error Set Type#}</li>
</ul>
</td>
<td>
{#link|Merging Error Sets#}
</td>
<td>
<pre>{#syntax#}const A = error{One};
const B = error{Two};
(A || B) == error{One, Two}{#endsyntax#}</pre>
</td>
</tr>
</tbody>
</table>
</div>
{#header_close#}
{#header_open|Precedence#}
<pre>{#syntax#}x() x[] x.y x.* x.?
a!b
x{}
!x -x -%x ~x &x ?x
* / % ** *% *| ||
+ - ++ +% -% +| -|
<< >> <<|
& ^ | orelse catch
== != < > <= >=
and
or
= *= *%= *|= /= %= += +%= +|= -= -%= -|= <<= <<|= >>= &= ^= |={#endsyntax#}</pre>
{#header_close#}
{#header_close#}
{#header_open|Arrays#}
{#code_begin|test|test_arrays#}
const expect = @import("std").testing.expect;
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
// array literal
const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
// get the size of an array
comptime {
assert(message.len == 5);
}
// A string literal is a single-item pointer to an array.
const same_message = "hello";
comptime {
assert(mem.eql(u8, &message, same_message));
}
test "iterate over an array" {
var sum: usize = 0;
for (message) |byte| {
sum += byte;
}
try expect(sum == 'h' + 'e' + 'l' * 2 + 'o');
}
// modifiable array
var some_integers: [100]i32 = undefined;
test "modify an array" {
for (some_integers) |*item, i| {
item.* = @intCast(i32, i);
}
try expect(some_integers[10] == 10);
try expect(some_integers[99] == 99);
}
// array concatenation works if the values are known
// at compile time
const part_one = [_]i32{ 1, 2, 3, 4 };
const part_two = [_]i32{ 5, 6, 7, 8 };
const all_of_it = part_one ++ part_two;
comptime {
assert(mem.eql(i32, &all_of_it, &[_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }));
}
// remember that string literals are arrays
const hello = "hello";
const world = "world";
const hello_world = hello ++ " " ++ world;
comptime {
assert(mem.eql(u8, hello_world, "hello world"));
}
// ** does repeating patterns
const pattern = "ab" ** 3;
comptime {
assert(mem.eql(u8, pattern, "ababab"));
}
// initialize an array to zero
const all_zero = [_]u16{0} ** 10;
comptime {
assert(all_zero.len == 10);
assert(all_zero[5] == 0);
}
// use compile-time code to initialize an array
var fancy_array = init: {
var initial_value: [10]Point = undefined;
for (initial_value) |*pt, i| {
pt.* = Point{
.x = @intCast(i32, i),
.y = @intCast(i32, i) * 2,
};
}
break :init initial_value;
};
const Point = struct {
x: i32,
y: i32,
};
test "compile-time array initialization" {
try expect(fancy_array[4].x == 4);
try expect(fancy_array[4].y == 8);
}
// call a function to initialize an array
var more_points = [_]Point{makePoint(3)} ** 10;
fn makePoint(x: i32) Point {
return Point{
.x = x,
.y = x * 2,
};
}
test "array initialization with function calls" {
try expect(more_points[4].x == 3);
try expect(more_points[4].y == 6);
try expect(more_points.len == 10);
}
{#code_end#}
{#see_also|for|Slices#}
{#header_open|Multidimensional Arrays#}
<p>
Multidimensional arrays can be created by nesting arrays:
</p>
{#code_begin|test|test_multidimensional_arrays#}
const std = @import("std");
const expect = std.testing.expect;
const mat4x4 = [4][4]f32{
[_]f32{ 1.0, 0.0, 0.0, 0.0 },
[_]f32{ 0.0, 1.0, 0.0, 1.0 },
[_]f32{ 0.0, 0.0, 1.0, 0.0 },
[_]f32{ 0.0, 0.0, 0.0, 1.0 },
};
test "multidimensional arrays" {
// Access the 2D array by indexing the outer array, and then the inner array.
try expect(mat4x4[1][1] == 1.0);
// Here we iterate with for loops.
for (mat4x4) |row, row_index| {
for (row) |cell, column_index| {
if (row_index == column_index) {
try expect(cell == 1.0);
}
}
}
}
{#code_end#}
{#header_close#}
{#header_open|Sentinel-Terminated Arrays#}
<p>
The syntax {#syntax#}[N:x]T{#endsyntax#} describes an array which has a sentinel element of value {#syntax#}x{#endsyntax#} at the
index corresponding to {#syntax#}len{#endsyntax#}.
</p>
{#code_begin|test|test_null_terminated_array#}
const std = @import("std");
const expect = std.testing.expect;
test "null terminated array" {
const array = [_:0]u8 {1, 2, 3, 4};
try expect(@TypeOf(array) == [4:0]u8);
try expect(array.len == 4);
try expect(array[4] == 0);
}
{#code_end#}
{#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Slices#}
{#header_close#}
{#header_close#}
{#header_open|Vectors#}
<p>
A vector is a group of booleans, {#link|Integers#}, {#link|Floats#}, or
{#link|Pointers#} which are operated on in parallel, using SIMD instructions if possible.
Vector types are created with the builtin function {#link|@Vector#}.
</p>
<p>
Vectors support the same builtin operators as their underlying base types.
These operations are performed element-wise, and return a vector of the same length
as the input vectors. This includes:
</p>
<ul>
<li>Arithmetic ({#syntax#}+{#endsyntax#}, {#syntax#}-{#endsyntax#}, {#syntax#}/{#endsyntax#}, {#syntax#}*{#endsyntax#},
{#syntax#}@divFloor{#endsyntax#}, {#syntax#}@sqrt{#endsyntax#}, {#syntax#}@ceil{#endsyntax#},
{#syntax#}@log{#endsyntax#}, etc.)</li>
<li>Bitwise operators ({#syntax#}>>{#endsyntax#}, {#syntax#}<<{#endsyntax#}, {#syntax#}&{#endsyntax#},
{#syntax#}|{#endsyntax#}, {#syntax#}~{#endsyntax#}, etc.)</li>
<li>Comparison operators ({#syntax#}<{#endsyntax#}, {#syntax#}>{#endsyntax#}, {#syntax#}=={#endsyntax#}, etc.)</li>
</ul>
<p>
It is prohibited to use a math operator on a mixture of scalars (individual numbers)
and vectors. Zig provides the {#link|@splat#} builtin to easily convert from scalars
to vectors, and it supports {#link|@reduce#} and array indexing syntax to convert
from vectors to scalars. Vectors also support assignment to and from fixed-length
arrays with comptime-known length.
</p>
<p>
For rearranging elements within and between vectors, Zig provides the {#link|@shuffle#} and {#link|@select#} functions.
</p>
<p>
Operations on vectors shorter than the target machine's native SIMD size will typically compile to single SIMD
instructions, while vectors longer than the target machine's native SIMD size will compile to multiple SIMD
instructions. If a given operation doesn't have SIMD support on the target architecture, the compiler will default
to operating on each vector element one at a time. Zig supports any comptime-known vector length up to 2^32-1,
although small powers of two (2-64) are most typical. Note that excessively long vector lengths (e.g. 2^20) may
result in compiler crashes on current versions of Zig.
</p>
{#code_begin|test|test_vector#}
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "Basic vector usage" {
// Vectors have a compile-time known length and base type.
const a = @Vector(4, i32){ 1, 2, 3, 4 };
const b = @Vector(4, i32){ 5, 6, 7, 8 };
// Math operations take place element-wise.
const c = a + b;
// Individual vector elements can be accessed using array indexing syntax.
try expectEqual(6, c[0]);
try expectEqual(8, c[1]);
try expectEqual(10, c[2]);
try expectEqual(12, c[3]);
}
test "Conversion between vectors, arrays, and slices" {
// Vectors and fixed-length arrays can be automatically assigned back and forth
var arr1: [4]f32 = [_]f32{ 1.1, 3.2, 4.5, 5.6 };
var vec: @Vector(4, f32) = arr1;
var arr2: [4]f32 = vec;
try expectEqual(arr1, arr2);
// You can also assign from a slice with comptime-known length to a vector using .*
const vec2: @Vector(2, f32) = arr1[1..3].*;
var slice: []const f32 = &arr1;
var offset: u32 = 1;
// To extract a comptime-known length from a runtime-known offset,
// first extract a new slice from the starting offset, then an array of
// comptime-known length
const vec3: @Vector(2, f32) = slice[offset..][0..2].*;
try expectEqual(slice[offset], vec2[0]);
try expectEqual(slice[offset + 1], vec2[1]);
try expectEqual(vec2, vec3);
}
{#code_end#}
<p>
TODO talk about C ABI interop<br>
TODO consider suggesting std.MultiArrayList
</p>
{#see_also|@splat|@shuffle|@select|@reduce#}
{#header_close#}
{#header_open|Pointers#}
<p>
Zig has two kinds of pointers: single-item and many-item.
</p>
<ul>
<li>{#syntax#}*T{#endsyntax#} - single-item pointer to exactly one item.
<ul>
<li>Supports deref syntax: {#syntax#}ptr.*{#endsyntax#}</li>
</ul>
</li>
<li>{#syntax#}[*]T{#endsyntax#} - many-item pointer to unknown number of items.
<ul>
<li>Supports index syntax: {#syntax#}ptr[i]{#endsyntax#}</li>
<li>Supports slice syntax: {#syntax#}ptr[start..end]{#endsyntax#}</li>
<li>Supports pointer arithmetic: {#syntax#}ptr + x{#endsyntax#}, {#syntax#}ptr - x{#endsyntax#}</li>
<li>{#syntax#}T{#endsyntax#} must have a known size, which means that it cannot be
{#syntax#}anyopaque{#endsyntax#} or any other {#link|opaque type|opaque#}.</li>
</ul>
</li>
</ul>
<p>These types are closely related to {#link|Arrays#} and {#link|Slices#}:</p>
<ul>
<li>{#syntax#}*[N]T{#endsyntax#} - pointer to N items, same as single-item pointer to an array.
<ul>
<li>Supports index syntax: {#syntax#}array_ptr[i]{#endsyntax#}</li>
<li>Supports slice syntax: {#syntax#}array_ptr[start..end]{#endsyntax#}</li>
<li>Supports len property: {#syntax#}array_ptr.len{#endsyntax#}</li>
</ul>
</li>
</ul>
<ul>
<li>{#syntax#}[]T{#endsyntax#} - is a slice (a fat pointer, which contains a pointer of type {#syntax#}[*]T{#endsyntax#} and a length).
<ul>
<li>Supports index syntax: {#syntax#}slice[i]{#endsyntax#}</li>
<li>Supports slice syntax: {#syntax#}slice[start..end]{#endsyntax#}</li>
<li>Supports len property: {#syntax#}slice.len{#endsyntax#}</li>
</ul>
</li>
</ul>
<p>Use {#syntax#}&x{#endsyntax#} to obtain a single-item pointer:</p>
{#code_begin|test|test_single_item_pointer#}
const expect = @import("std").testing.expect;
test "address of syntax" {
// Get the address of a variable:
const x: i32 = 1234;
const x_ptr = &x;
// Dereference a pointer:
try expect(x_ptr.* == 1234);
// When you get the address of a const variable, you get a const single-item pointer.
try expect(@TypeOf(x_ptr) == *const i32);
// If you want to mutate the value, you'd need an address of a mutable variable:
var y: i32 = 5678;
const y_ptr = &y;
try expect(@TypeOf(y_ptr) == *i32);
y_ptr.* += 1;
try expect(y_ptr.* == 5679);
}
test "pointer array access" {
// Taking an address of an individual element gives a
// single-item pointer. This kind of pointer
// does not support pointer arithmetic.
var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
const ptr = &array[2];
try expect(@TypeOf(ptr) == *u8);
try expect(array[2] == 3);
ptr.* += 1;
try expect(array[2] == 4);
}
{#code_end#}
<p>
Zig supports pointer arithmetic. It's better to assign the pointer to {#syntax#}[*]T{#endsyntax#} and increment that variable. For example, directly incrementing the pointer from a slice will corrupt it.
</p>
{#code_begin|test|test_pointer_arithmetic#}
const expect = @import("std").testing.expect;
test "pointer arithmetic with many-item pointer" {
const array = [_]i32{ 1, 2, 3, 4 };
var ptr: [*]const i32 = &array;
try expect(ptr[0] == 1);
ptr += 1;
try expect(ptr[0] == 2);
}
test "pointer arithmetic with slices" {
var array = [_]i32{ 1, 2, 3, 4 };
var length: usize = 0;
var slice = array[length..array.len];
try expect(slice[0] == 1);
try expect(slice.len == 4);
slice.ptr += 1;
// now the slice is in an bad state since len has not been updated
try expect(slice[0] == 2);
try expect(slice.len == 4);
}
{#code_end#}
<p>
In Zig, we generally prefer {#link|Slices#} rather than {#link|Sentinel-Terminated Pointers#}.
You can turn an array or pointer into a slice using slice syntax.
</p>
<p>
Slices have bounds checking and are therefore protected
against this kind of undefined behavior. This is one reason
we prefer slices to pointers.
</p>
{#code_begin|test|test_slice_bounds#}
const expect = @import("std").testing.expect;
test "pointer slicing" {
var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var start: usize = 2;
const slice = array[start..4];
try expect(slice.len == 2);
try expect(array[3] == 4);
slice[1] += 1;
try expect(array[3] == 5);
}
{#code_end#}
<p>Pointers work at compile-time too, as long as the code does not depend on
an undefined memory layout:</p>
{#code_begin|test|test_comptime_pointers#}
const expect = @import("std").testing.expect;
test "comptime pointers" {
comptime {
var x: i32 = 1;
const ptr = &x;
ptr.* += 1;
x += 1;
try expect(ptr.* == 3);
}
}
{#code_end#}
<p>To convert an integer address into a pointer, use {#syntax#}@intToPtr{#endsyntax#}.
To convert a pointer to an integer, use {#syntax#}@ptrToInt{#endsyntax#}:</p>
{#code_begin|test|test_integer_pointer_conversion#}
const expect = @import("std").testing.expect;
test "@ptrToInt and @intToPtr" {
const ptr = @intToPtr(*i32, 0xdeadbee0);
const addr = @ptrToInt(ptr);
try expect(@TypeOf(addr) == usize);
try expect(addr == 0xdeadbee0);
}
{#code_end#}
<p>Zig is able to preserve memory addresses in comptime code, as long as
the pointer is never dereferenced:</p>
{#code_begin|test|test_comptime_pointer_conversion#}
const expect = @import("std").testing.expect;
test "comptime @intToPtr" {
comptime {
// Zig is able to do this at compile-time, as long as
// ptr is never dereferenced.
const ptr = @intToPtr(*i32, 0xdeadbee0);
const addr = @ptrToInt(ptr);
try expect(@TypeOf(addr) == usize);
try expect(addr == 0xdeadbee0);
}
}
{#code_end#}
{#see_also|Optional Pointers|@intToPtr|@ptrToInt|C Pointers#}
{#header_open|volatile#}
<p>Loads and stores are assumed to not have side effects. If a given load or store
should have side effects, such as Memory Mapped Input/Output (MMIO), use {#syntax#}volatile{#endsyntax#}.
In the following code, loads and stores with {#syntax#}mmio_ptr{#endsyntax#} are guaranteed to all happen
and in the same order as in source code:</p>
{#code_begin|test|test_volatile#}
const expect = @import("std").testing.expect;
test "volatile" {
const mmio_ptr = @intToPtr(*volatile u8, 0x12345678);
try expect(@TypeOf(mmio_ptr) == *volatile u8);
}
{#code_end#}
<p>
Note that {#syntax#}volatile{#endsyntax#} is unrelated to concurrency and {#link|Atomics#}.
If you see code that is using {#syntax#}volatile{#endsyntax#} for something other than Memory Mapped
Input/Output, it is probably a bug.
</p>
{#header_close#}
<p>
To convert one pointer type to another, use {#link|@ptrCast#}. This is an unsafe
operation that Zig cannot protect you against. Use {#syntax#}@ptrCast{#endsyntax#} only when other
conversions are not possible.
</p>
{#code_begin|test|test_pointer_casting#}
const std = @import("std");
const expect = std.testing.expect;
test "pointer casting" {
const bytes align(@alignOf(u32)) = [_]u8{ 0x12, 0x12, 0x12, 0x12 };
const u32_ptr = @ptrCast(*const u32, &bytes);
try expect(u32_ptr.* == 0x12121212);
// Even this example is contrived - there are better ways to do the above than
// pointer casting. For example, using a slice narrowing cast:
const u32_value = std.mem.bytesAsSlice(u32, bytes[0..])[0];
try expect(u32_value == 0x12121212);
// And even another way, the most straightforward way to do it:
try expect(@bitCast(u32, bytes) == 0x12121212);
}
test "pointer child type" {
// pointer types have a `child` field which tells you the type they point to.
try expect(@typeInfo(*u32).Pointer.child == u32);
}
{#code_end#}
{#header_open|Alignment#}
<p>
Each type has an <strong>alignment</strong> - a number of bytes such that,
when a value of the type is loaded from or stored to memory,
the memory address must be evenly divisible by this number. You can use
{#link|@alignOf#} to find out this value for any type.
</p>
<p>
Alignment depends on the CPU architecture, but is always a power of two, and
less than {#syntax#}1 << 29{#endsyntax#}.
</p>
<p>
In Zig, a pointer type has an alignment value. If the value is equal to the
alignment of the underlying type, it can be omitted from the type:
</p>
{#code_begin|test|test_variable_alignment#}
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
test "variable alignment" {
var x: i32 = 1234;
const align_of_i32 = @alignOf(@TypeOf(x));
try expect(@TypeOf(&x) == *i32);
try expect(*i32 == *align(align_of_i32) i32);
if (builtin.target.cpu.arch == .x86_64) {
try expect(@typeInfo(*i32).Pointer.alignment == 4);
}
}
{#code_end#}
<p>In the same way that a {#syntax#}*i32{#endsyntax#} can be {#link|coerced|Type Coercion#} to a
{#syntax#}*const i32{#endsyntax#}, a pointer with a larger alignment can be implicitly
cast to a pointer with a smaller alignment, but not vice versa.
</p>
<p>
You can specify alignment on variables and functions. If you do this, then
pointers to them get the specified alignment:
</p>
{#code_begin|test|test_variable_func_alignment#}
const expect = @import("std").testing.expect;
var foo: u8 align(4) = 100;
test "global variable alignment" {
try expect(@typeInfo(@TypeOf(&foo)).Pointer.alignment == 4);
try expect(@TypeOf(&foo) == *align(4) u8);
const as_pointer_to_array: *align(4) [1]u8 = &foo;
const as_slice: []align(4) u8 = as_pointer_to_array;
const as_unaligned_slice: []u8 = as_slice;
try expect(as_unaligned_slice[0] == 100);
}
fn derp() align(@sizeOf(usize) * 2) i32 {
return 1234;
}
fn noop1() align(1) void {}
fn noop4() align(4) void {}
test "function alignment" {
try expect(derp() == 1234);
try expect(@TypeOf(noop1) == fn () align(1) void);
try expect(@TypeOf(noop4) == fn () align(4) void);
noop1();
noop4();
}
{#code_end#}
<p>
If you have a pointer or a slice that has a small alignment, but you know that it actually
has a bigger alignment, use {#link|@alignCast#} to change the
pointer into a more aligned pointer. This is a no-op at runtime, but inserts a
{#link|safety check|Incorrect Pointer Alignment#}:
</p>
{#code_begin|test_safety|test_incorrect_pointer_alignment|incorrect alignment#}
const std = @import("std");
test "pointer alignment safety" {
var array align(4) = [_]u32{ 0x11111111, 0x11111111 };
const bytes = std.mem.sliceAsBytes(array[0..]);
try std.testing.expect(foo(bytes) == 0x11111111);
}
fn foo(bytes: []u8) u32 {
const slice4 = bytes[1..5];
const int_slice = std.mem.bytesAsSlice(u32, @alignCast(4, slice4));
return int_slice[0];
}
{#code_end#}
{#header_close#}
{#header_open|allowzero#}
<p>
This pointer attribute allows a pointer to have address zero. This is only ever needed on the
freestanding OS target, where the address zero is mappable. If you want to represent null pointers, use
{#link|Optional Pointers#} instead. {#link|Optional Pointers#} with {#syntax#}allowzero{#endsyntax#}
are not the same size as pointers. In this code example, if the pointer
did not have the {#syntax#}allowzero{#endsyntax#} attribute, this would be a
{#link|Pointer Cast Invalid Null#} panic:
</p>
{#code_begin|test|test_allowzero#}
const std = @import("std");
const expect = std.testing.expect;
test "allowzero" {
var zero: usize = 0;
var ptr = @intToPtr(*allowzero i32, zero);
try expect(@ptrToInt(ptr) == 0);
}
{#code_end#}
{#header_close#}
{#header_open|Sentinel-Terminated Pointers#}
<p>
The syntax {#syntax#}[*:x]T{#endsyntax#} describes a pointer that
has a length determined by a sentinel value. This provides protection
against buffer overflow and overreads.
</p>
{#code_begin|exe_build_err|sentinel-terminated_pointer#}
{#link_libc#}
const std = @import("std");
// This is also available as `std.c.printf`.
pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
pub fn main() anyerror!void {
_ = printf("Hello, world!\n"); // OK
const msg = "Hello, world!\n";
const non_null_terminated_msg: [msg.len]u8 = msg.*;
_ = printf(&non_null_terminated_msg);
}
{#code_end#}
{#see_also|Sentinel-Terminated Slices|Sentinel-Terminated Arrays#}
{#header_close#}
{#header_close#}
{#header_open|Slices#}
{#code_begin|test_safety|test_basic_slices|index out of bounds#}
const expect = @import("std").testing.expect;
test "basic slices" {
var array = [_]i32{ 1, 2, 3, 4 };
// A slice is a pointer and a length. The difference between an array and
// a slice is that the array's length is part of the type and known at
// compile-time, whereas the slice's length is known at runtime.
// Both can be accessed with the `len` field.
var known_at_runtime_zero: usize = 0;
const slice = array[known_at_runtime_zero..array.len];
try expect(@TypeOf(slice) == []i32);
try expect(&slice[0] == &array[0]);
try expect(slice.len == array.len);
// If you slice with comptime-known start and end positions, the result is
// a pointer to an array, rather than a slice.
const array_ptr = array[0..array.len];
try expect(@TypeOf(array_ptr) == *[array.len]i32);
// Using the address-of operator on a slice gives a single-item pointer,
// while using the `ptr` field gives a many-item pointer.
try expect(@TypeOf(slice.ptr) == [*]i32);
try expect(@TypeOf(&slice[0]) == *i32);
try expect(@ptrToInt(slice.ptr) == @ptrToInt(&slice[0]));
// Slices have array bounds checking. If you try to access something out
// of bounds, you'll get a safety check failure:
slice[10] += 1;
// Note that `slice.ptr` does not invoke safety checking, while `&slice[0]`
// asserts that the slice has len >= 1.
}
{#code_end#}
<p>This is one reason we prefer slices to pointers.</p>
{#code_begin|test|test_slices#}
const std = @import("std");
const expect = std.testing.expect;
const mem = std.mem;
const fmt = std.fmt;
test "using slices for strings" {
// Zig has no concept of strings. String literals are const pointers
// to null-terminated arrays of u8, and by convention parameters
// that are "strings" are expected to be UTF-8 encoded slices of u8.
// Here we coerce *const [5:0]u8 and *const [6:0]u8 to []const u8
const hello: []const u8 = "hello";
const world: []const u8 = "世界";
var all_together: [100]u8 = undefined;
// You can use slice syntax with at least one runtime-know index on an
// array to convert an array into a slice.
var start : usize = 0;
const all_together_slice = all_together[start..];
// String concatenation example.
const hello_world = try fmt.bufPrint(all_together_slice, "{s} {s}", .{ hello, world });
// Generally, you can use UTF-8 and not worry about whether something is a
// string. If you don't need to deal with individual characters, no need
// to decode.
try expect(mem.eql(u8, hello_world, "hello 世界"));
}
test "slice pointer" {
var a: []u8 = undefined;
try expect(@TypeOf(a) == []u8);
var array: [10]u8 = undefined;
const ptr = &array;
try expect(@TypeOf(ptr) == *[10]u8);
// A pointer to an array can be sliced just like an array:
var start: usize = 0;
var end: usize = 5;
const slice = ptr[start..end];
slice[2] = 3;
try expect(slice[2] == 3);
// The slice is mutable because we sliced a mutable pointer.
try expect(@TypeOf(slice) == []u8);
// Again, slicing with comptime-known indexes will produce another pointer
// to an array:
const ptr2 = slice[2..3];
try expect(ptr2.len == 1);
try expect(ptr2[0] == 3);
try expect(@TypeOf(ptr2) == *[1]u8);
}
{#code_end#}
{#see_also|Pointers|for|Arrays#}
{#header_open|Sentinel-Terminated Slices#}
<p>
The syntax {#syntax#}[:x]T{#endsyntax#} is a slice which has a runtime-known length
and also guarantees a sentinel value at the element indexed by the length. The type does not
guarantee that there are no sentinel elements before that. Sentinel-terminated slices allow element
access to the {#syntax#}len{#endsyntax#} index.
</p>
{#code_begin|test|test_null_terminated_slice#}
const std = @import("std");
const expect = std.testing.expect;
test "null terminated slice" {
const slice: [:0]const u8 = "hello";
try expect(slice.len == 5);
try expect(slice[5] == 0);
}
{#code_end#}
<p>
Sentinel-terminated slices can also be created using a variation of the slice syntax
{#syntax#}data[start..end :x]{#endsyntax#}, where {#syntax#}data{#endsyntax#} is a many-item pointer,
array or slice and {#syntax#}x{#endsyntax#} is the sentinel value.
</p>
{#code_begin|test|test_null_terminated_slicing#}
const std = @import("std");
const expect = std.testing.expect;
test "null terminated slicing" {
var array = [_]u8{ 3, 2, 1, 0, 3, 2, 1, 0 };
var runtime_length: usize = 3;
const slice = array[0..runtime_length :0];
try expect(@TypeOf(slice) == [:0]u8);
try expect(slice.len == 3);
}
{#code_end#}
<p>
Sentinel-terminated slicing asserts that the element in the sentinel position of the backing data is
actually the sentinel value. If this is not the case, safety-protected {#link|Undefined Behavior#} results.
</p>
{#code_begin|test_safety|test_sentinel_mismatch|sentinel mismatch#}
const std = @import("std");
const expect = std.testing.expect;
test "sentinel mismatch" {
var array = [_]u8{ 3, 2, 1, 0 };
// Creating a sentinel-terminated slice from the array with a length of 2
// will result in the value `1` occupying the sentinel element position.
// This does not match the indicated sentinel value of `0` and will lead
// to a runtime panic.
var runtime_length: usize = 2;
const slice = array[0..runtime_length :0];
_ = slice;
}
{#code_end#}
{#see_also|Sentinel-Terminated Pointers|Sentinel-Terminated Arrays#}
{#header_close#}
{#header_close#}
{#header_open|struct#}
{#code_begin|test|test_structs#}
// Declare a struct.
// Zig gives no guarantees about the order of fields and the size of
// the struct but the fields are guaranteed to be ABI-aligned.
const Point = struct {
x: f32,
y: f32,
};
// Maybe we want to pass it to OpenGL so we want to be particular about
// how the bytes are arranged.
const Point2 = packed struct {
x: f32,
y: f32,
};
// Declare an instance of a struct.
const p = Point {
.x = 0.12,
.y = 0.34,
};
// Maybe we're not ready to fill out some of the fields.
var p2 = Point {
.x = 0.12,
.y = undefined,
};
// Structs can have methods
// Struct methods are not special, they are only namespaced
// functions that you can call with dot syntax.
const Vec3 = struct {
x: f32,
y: f32,
z: f32,
pub fn init(x: f32, y: f32, z: f32) Vec3 {
return Vec3 {
.x = x,
.y = y,
.z = z,
};
}
pub fn dot(self: Vec3, other: Vec3) f32 {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
};
const expect = @import("std").testing.expect;
test "dot product" {
const v1 = Vec3.init(1.0, 0.0, 0.0);
const v2 = Vec3.init(0.0, 1.0, 0.0);
try expect(v1.dot(v2) == 0.0);
// Other than being available to call with dot syntax, struct methods are
// not special. You can reference them as any other declaration inside
// the struct:
try expect(Vec3.dot(v1, v2) == 0.0);
}
// Structs can have declarations.
// Structs can have 0 fields.
const Empty = struct {
pub const PI = 3.14;
};
test "struct namespaced variable" {
try expect(Empty.PI == 3.14);
try expect(@sizeOf(Empty) == 0);
// you can still instantiate an empty struct
const does_nothing = Empty {};
_ = does_nothing;
}
// struct field order is determined by the compiler for optimal performance.
// however, you can still calculate a struct base pointer given a field pointer:
fn setYBasedOnX(x: *f32, y: f32) void {
const point = @fieldParentPtr(Point, "x", x);
point.y = y;
}
test "field parent pointer" {
var point = Point {
.x = 0.1234,
.y = 0.5678,
};
setYBasedOnX(&point.x, 0.9);
try expect(point.y == 0.9);
}
// You can return a struct from a function. This is how we do generics
// in Zig:
fn LinkedList(comptime T: type) type {
return struct {
pub const Node = struct {
prev: ?*Node,
next: ?*Node,
data: T,
};
first: ?*Node,
last: ?*Node,
len: usize,
};
}
test "linked list" {
// Functions called at compile-time are memoized. This means you can
// do this:
try expect(LinkedList(i32) == LinkedList(i32));
var list = LinkedList(i32) {
.first = null,
.last = null,
.len = 0,
};
try expect(list.len == 0);
// Since types are first class values you can instantiate the type
// by assigning it to a variable:
const ListOfInts = LinkedList(i32);
try expect(ListOfInts == LinkedList(i32));
var node = ListOfInts.Node {
.prev = null,
.next = null,
.data = 1234,
};
var list2 = LinkedList(i32) {
.first = &node,
.last = &node,
.len = 1,
};
// When using a pointer to a struct, fields can be accessed directly,
// without explicitly dereferencing the pointer.
// So you can do
try expect(list2.first.?.data == 1234);
// instead of try expect(list2.first.?.*.data == 1234);
}
{#code_end#}
{#header_open|Default Field Values#}
<p>
Each struct field may have an expression indicating the default field value. Such expressions
are executed at {#link|comptime#}, and allow the field to be omitted in a struct literal expression:
</p>
{#code_begin|test|test_struct_default_field_values#}
const Foo = struct {
a: i32 = 1234,
b: i32,
};
test "default struct initialization fields" {
const x = Foo{
.b = 5,
};
if (x.a + x.b != 1239) {
@compileError("it's even comptime-known!");
}
}
{#code_end#}
{#header_close#}
{#header_open|extern struct#}
<p>An {#syntax#}extern struct{#endsyntax#} has in-memory layout guaranteed to match the
C ABI for the target.</p>
<p>This kind of struct should only be used for compatibility with the C ABI. Every other
use case should be solved with {#link|packed struct#} or normal {#link|struct#}.</p>
{#see_also|extern union|extern enum#}
{#header_close#}
{#header_open|packed struct#}
<p>
Unlike normal structs, {#syntax#}packed{#endsyntax#} structs have guaranteed in-memory layout:
</p>
<ul>
<li>Fields remain in the order declared, least to most significant.</li>
<li>There is no padding between fields.</li>
<li>Zig supports arbitrary width {#link|Integers#} and although normally, integers with fewer
than 8 bits will still use 1 byte of memory, in packed structs, they use
exactly their bit width.
</li>
<li>{#syntax#}bool{#endsyntax#} fields use exactly 1 bit.</li>
<li>An {#link|enum#} field uses exactly the bit width of its integer tag type.</li>
<li>A {#link|packed union#} field uses exactly the bit width of the union field with
the largest bit width.</li>
<li>Non-ABI-aligned fields are packed into the smallest possible
ABI-aligned integers in accordance with the target endianness.
</li>
</ul>
<p>
This means that a {#syntax#}packed struct{#endsyntax#} can participate
in a {#link|@bitCast#} or a {#link|@ptrCast#} to reinterpret memory.
This even works at {#link|comptime#}:
</p>
{#code_begin|test|test_packed_structs#}
const std = @import("std");
const native_endian = @import("builtin").target.cpu.arch.endian();
const expect = std.testing.expect;
const Full = packed struct {
number: u16,
};
const Divided = packed struct {
half1: u8,
quarter3: u4,
quarter4: u4,
};
test "@bitCast between packed structs" {
try doTheTest();
comptime try doTheTest();
}
fn doTheTest() !void {
try expect(@sizeOf(Full) == 2);
try expect(@sizeOf(Divided) == 2);
var full = Full{ .number = 0x1234 };
var divided = @bitCast(Divided, full);
try expect(divided.half1 == 0x34);
try expect(divided.quarter3 == 0x2);
try expect(divided.quarter4 == 0x1);
var ordered = @bitCast([2]u8, full);
switch (native_endian) {
.Big => {
try expect(ordered[0] == 0x12);
try expect(ordered[1] == 0x34);
},
.Little => {
try expect(ordered[0] == 0x34);
try expect(ordered[1] == 0x12);
},
}
}
{#code_end#}
<p>
Zig allows the address to be taken of a non-byte-aligned field:
</p>
{#code_begin|test|test_pointer_to_non-byte_aligned_field#}
const std = @import("std");
const expect = std.testing.expect;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var foo = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointer to non-byte-aligned field" {
const ptr = &foo.b;
try expect(ptr.* == 2);
}
{#code_end#}
<p>
However, the pointer to a non-byte-aligned field has special properties and cannot
be passed when a normal pointer is expected:
</p>
{#code_begin|test_err|test_misaligned_pointer|expected type#}
const std = @import("std");
const expect = std.testing.expect;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var bit_field = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointer to non-bit-aligned field" {
try expect(bar(&bit_field.b) == 2);
}
fn bar(x: *const u3) u3 {
return x.*;
}
{#code_end#}
<p>
In this case, the function {#syntax#}bar{#endsyntax#} cannot be called because the pointer
to the non-ABI-aligned field mentions the bit offset, but the function expects an ABI-aligned pointer.
</p>
<p>
Pointers to non-ABI-aligned fields share the same address as the other fields within their host integer:
</p>
{#code_begin|test|test_packed_struct_field_address#}
const std = @import("std");
const expect = std.testing.expect;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var bit_field = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointers of sub-byte-aligned fields share addresses" {
try expect(@ptrToInt(&bit_field.a) == @ptrToInt(&bit_field.b));
try expect(@ptrToInt(&bit_field.a) == @ptrToInt(&bit_field.c));
}
{#code_end#}
<p>
This can be observed with {#link|@bitOffsetOf#} and {#link|offsetOf#}:
</p>
{#code_begin|test|test_bitOffsetOf_offsetOf#}
const std = @import("std");
const expect = std.testing.expect;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
test "pointer to non-bit-aligned field" {
comptime {
try expect(@bitOffsetOf(BitField, "a") == 0);
try expect(@bitOffsetOf(BitField, "b") == 3);
try expect(@bitOffsetOf(BitField, "c") == 6);
try expect(@offsetOf(BitField, "a") == 0);
try expect(@offsetOf(BitField, "b") == 0);
try expect(@offsetOf(BitField, "c") == 0);
}
}
{#code_end#}
<p>
Packed structs have the same alignment as their backing integer, however, overaligned
pointers to packed structs can override this:
</p>
{#code_begin|test|test_overaligned_packed_struct#}
const std = @import("std");
const expect = std.testing.expect;
const S = packed struct {
a: u32,
b: u32,
};
test "overaligned pointer to packed struct" {
var foo: S align(4) = .{ .a = 1, .b = 2 };
const ptr: *align(4) S = &foo;
const ptr_to_b: *u32 = &ptr.b;
try expect(ptr_to_b.* == 2);
}
{#code_end#}
<p>
It's also possible to set alignment of struct fields:
</p>
{#code_begin|test|test_aligned_struct_fields#}
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "aligned struct fields" {
const S = struct {
a: u32 align(2),
b: u32 align(64),
};
var foo = S{ .a = 1, .b = 2 };
try expectEqual(64, @alignOf(S));
try expectEqual(*align(2) u32, @TypeOf(&foo.a));
try expectEqual(*align(64) u32, @TypeOf(&foo.b));
}
{#code_end#}
<p>
Using packed structs with {#link|volatile#} is problematic, and may be a compile error in the future.
For details on this subscribe to
<a href="https://github.com/ziglang/zig/issues/1761">this issue</a>.
TODO update these docs with a recommendation on how to use packed structs with MMIO
(the use case for volatile packed structs) once this issue is resolved.
Don't worry, there will be a good solution for this use case in zig.
</p>
{#header_close#}
{#header_open|Struct Naming#}
<p>Since all structs are anonymous, Zig infers the type name based on a few rules.</p>
<ul>
<li>If the struct is in the initialization expression of a variable, it gets named after
that variable.</li>
<li>If the struct is in the {#syntax#}return{#endsyntax#} expression, it gets named after
the function it is returning from, with the parameter values serialized.</li>
<li>Otherwise, the struct gets a name such as <code>(filename.funcname.__struct_ID)</code>.</li>
<li>If the struct is declared inside another struct, it gets named after both the parent
struct and the name inferred by the previous rules, separated by a dot.</li>
</ul>
{#code_begin|exe|struct_name#}
const std = @import("std");
pub fn main() void {
const Foo = struct {};
std.debug.print("variable: {s}\n", .{@typeName(Foo)});
std.debug.print("anonymous: {s}\n", .{@typeName(struct {})});
std.debug.print("function: {s}\n", .{@typeName(List(i32))});
}
fn List(comptime T: type) type {
return struct {
x: T,
};
}
{#code_end#}
{#header_close#}
{#header_open|Anonymous Struct Literals#}
<p>
Zig allows omitting the struct type of a literal. When the result is {#link|coerced|Type Coercion#},
the struct literal will directly instantiate the {#link|result location|Result Location Semantics#},
with no copy:
</p>
{#code_begin|test|test_struct_result#}
const std = @import("std");
const expect = std.testing.expect;
const Point = struct {x: i32, y: i32};
test "anonymous struct literal" {
var pt: Point = .{
.x = 13,
.y = 67,
};
try expect(pt.x == 13);
try expect(pt.y == 67);
}
{#code_end#}
<p>
The struct type can be inferred. Here the {#link|result location|Result Location Semantics#}
does not include a type, and so Zig infers the type:
</p>
{#code_begin|test|test_anonymous_struct#}
const std = @import("std");
const expect = std.testing.expect;
test "fully anonymous struct" {
try dump(.{
.int = @as(u32, 1234),
.float = @as(f64, 12.34),
.b = true,
.s = "hi",
});
}
fn dump(args: anytype) !void {
try expect(args.int == 1234);
try expect(args.float == 12.34);
try expect(args.b);
try expect(args.s[0] == 'h');
try expect(args.s[1] == 'i');
}
{#code_end#}
{#header_close#}
{#header_open|Tuples#}
<p>
Anonymous structs can be created without specifying field names, and are referred to as "tuples".
</p>
<p>
The fields are implicitly named using numbers starting from 0. Because their names are integers,
they cannot be accessed with {#syntax#}.{#endsyntax#} syntax without also wrapping them in
{#syntax#}@""{#endsyntax#}. Names inside {#syntax#}@""{#endsyntax#} are always recognised as
{#link|identifiers|Identifiers#}.
</p>
<p>
Like arrays, tuples have a .len field, can be indexed (provided the index is comptime-known)
and work with the ++ and ** operators. They can also be iterated over with {#link|inline for#}.
</p>
{#code_begin|test|test_tuples#}
const std = @import("std");
const expect = std.testing.expect;
test "tuple" {
const values = .{
@as(u32, 1234),
@as(f64, 12.34),
true,
"hi",
} ++ .{false} ** 2;
try expect(values[0] == 1234);
try expect(values[4] == false);
inline for (values) |v, i| {
if (i != 2) continue;
try expect(v);
}
try expect(values.len == 6);
try expect(values.@"3"[0] == 'h');
}
{#code_end#}
{#header_close#}
{#see_also|comptime|@fieldParentPtr#}
{#header_close#}
{#header_open|enum#}
{#code_begin|test|test_enums#}
const expect = @import("std").testing.expect;
const mem = @import("std").mem;
// Declare an enum.
const Type = enum {
ok,
not_ok,
};
// Declare a specific enum field.
const c = Type.ok;
// If you want access to the ordinal value of an enum, you
// can specify the tag type.
const Value = enum(u2) {
zero,
one,
two,
};
// Now you can cast between u2 and Value.
// The ordinal value starts from 0, counting up by 1 from the previous member.
test "enum ordinal value" {
try expect(@enumToInt(Value.zero) == 0);
try expect(@enumToInt(Value.one) == 1);
try expect(@enumToInt(Value.two) == 2);
}
// You can override the ordinal value for an enum.
const Value2 = enum(u32) {
hundred = 100,
thousand = 1000,
million = 1000000,
};
test "set enum ordinal value" {
try expect(@enumToInt(Value2.hundred) == 100);
try expect(@enumToInt(Value2.thousand) == 1000);
try expect(@enumToInt(Value2.million) == 1000000);
}
// You can also override only some values.
const Value3 = enum(u4) {
a,
b = 8,
c,
d = 4,
e,
};
test "enum implicit ordinal values and overridden values" {
try expect(@enumToInt(Value3.a) == 0);
try expect(@enumToInt(Value3.b) == 8);
try expect(@enumToInt(Value3.c) == 9);
try expect(@enumToInt(Value3.d) == 4);
try expect(@enumToInt(Value3.e) == 5);
}
// Enums can have methods, the same as structs and unions.
// Enum methods are not special, they are only namespaced
// functions that you can call with dot syntax.
const Suit = enum {
clubs,
spades,
diamonds,
hearts,
pub fn isClubs(self: Suit) bool {
return self == Suit.clubs;
}
};
test "enum method" {
const p = Suit.spades;
try expect(!p.isClubs());
}
// An enum can be switched upon.
const Foo = enum {
string,
number,
none,
};
test "enum switch" {
const p = Foo.number;
const what_is_it = switch (p) {
Foo.string => "this is a string",
Foo.number => "this is a number",
Foo.none => "this is a none",
};
try expect(mem.eql(u8, what_is_it, "this is a number"));
}
// @typeInfo can be used to access the integer tag type of an enum.
const Small = enum {
one,
two,
three,
four,
};
test "std.meta.Tag" {
try expect(@typeInfo(Small).Enum.tag_type == u2);
}
// @typeInfo tells us the field count and the fields names:
test "@typeInfo" {
try expect(@typeInfo(Small).Enum.fields.len == 4);
try expect(mem.eql(u8, @typeInfo(Small).Enum.fields[1].name, "two"));
}
// @tagName gives a [:0]const u8 representation of an enum value:
test "@tagName" {
try expect(mem.eql(u8, @tagName(Small.three), "three"));
}
{#code_end#}
{#see_also|@typeInfo|@tagName|@sizeOf#}
{#header_open|extern enum#}
<p>
By default, enums are not guaranteed to be compatible with the C ABI:
</p>
{#code_begin|obj_err|enum_export_error|parameter of type 'enum_export_error.Foo' not allowed in function with calling convention 'C'#}
const Foo = enum { a, b, c };
export fn entry(foo: Foo) void { _ = foo; }
{#code_end#}
<p>
For a C-ABI-compatible enum, provide an explicit tag type to
the enum:
</p>
{#code_begin|obj|enum_export#}
const Foo = enum(c_int) { a, b, c };
export fn entry(foo: Foo) void { _ = foo; }
{#code_end#}
{#header_close#}
{#header_open|Enum Literals#}
<p>
Enum literals allow specifying the name of an enum field without specifying the enum type:
</p>
{#code_begin|test|test_enum_literals#}
const std = @import("std");
const expect = std.testing.expect;
const Color = enum {
auto,
off,
on,
};
test "enum literals" {
const color1: Color = .auto;
const color2 = Color.auto;
try expect(color1 == color2);
}
test "switch using enum literals" {
const color = Color.on;
const result = switch (color) {
.auto => false,
.on => true,
.off => false,
};
try expect(result);
}
{#code_end#}
{#header_close#}
{#header_open|Non-exhaustive enum#}
<p>
A Non-exhaustive enum can be created by adding a trailing '_' field.
It must specify a tag type and cannot consume every enumeration value.
</p>
<p>
{#link|@intToEnum#} on a non-exhaustive enum involves the safety semantics
of {#link|@intCast#} to the integer tag type, but beyond that always results in
a well-defined enum value.
</p>
<p>
A switch on a non-exhaustive enum can include a '_' prong as an alternative to an {#syntax#}else{#endsyntax#} prong
with the difference being that it makes it a compile error if all the known tag names are not handled by the switch.
</p>
{#code_begin|test|test_switch_non-exhaustive#}
const std = @import("std");
const expect = std.testing.expect;
const Number = enum(u8) {
one,
two,
three,
_,
};
test "switch on non-exhaustive enum" {
const number = Number.one;
const result = switch (number) {
.one => true,
.two,
.three => false,
_ => false,
};
try expect(result);
const is_one = switch (number) {
.one => true,
else => false,
};
try expect(is_one);
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|union#}
<p>
A bare {#syntax#}union{#endsyntax#} defines a set of possible types that a value
can be as a list of fields. Only one field can be active at a time.
The in-memory representation of bare unions is not guaranteed.
Bare unions cannot be used to reinterpret memory. For that, use {#link|@ptrCast#},
or use an {#link|extern union#} or a {#link|packed union#} which have
guaranteed in-memory layout.
{#link|Accessing the non-active field|Wrong Union Field Access#} is
safety-checked {#link|Undefined Behavior#}:
</p>
{#code_begin|test_err|test_wrong_union_access|access of union field 'float' while field 'int' is active#}
const Payload = union {
int: i64,
float: f64,
boolean: bool,
};
test "simple union" {
var payload = Payload{ .int = 1234 };
payload.float = 12.34;
}
{#code_end#}
<p>You can activate another field by assigning the entire union:</p>
{#code_begin|test|test_simple_union#}
const std = @import("std");
const expect = std.testing.expect;
const Payload = union {
int: i64,
float: f64,
boolean: bool,
};
test "simple union" {
var payload = Payload{ .int = 1234 };
try expect(payload.int == 1234);
payload = Payload{ .float = 12.34 };
try expect(payload.float == 12.34);
}
{#code_end#}
<p>
In order to use {#link|switch#} with a union, it must be a {#link|Tagged union#}.
</p>
<p>
To initialize a union when the tag is a {#link|comptime#}-known name, see {#link|@unionInit#}.
</p>
{#header_open|Tagged union#}
<p>Unions can be declared with an enum tag type.
This turns the union into a <em>tagged</em> union, which makes it eligible
to use with {#link|switch#} expressions.
Tagged unions coerce to their tag type: {#link|Type Coercion: Unions and Enums#}.
</p>
{#code_begin|test|test_tagged_union#}
const std = @import("std");
const expect = std.testing.expect;
const ComplexTypeTag = enum {
ok,
not_ok,
};
const ComplexType = union(ComplexTypeTag) {
ok: u8,
not_ok: void,
};
test "switch on tagged union" {
const c = ComplexType{ .ok = 42 };
try expect(@as(ComplexTypeTag, c) == ComplexTypeTag.ok);
switch (c) {
ComplexTypeTag.ok => |value| try expect(value == 42),
ComplexTypeTag.not_ok => unreachable,
}
}
test "get tag type" {
try expect(std.meta.Tag(ComplexType) == ComplexTypeTag);
}
{#code_end#}
<p>In order to modify the payload of a tagged union in a switch expression,
place a {#syntax#}*{#endsyntax#} before the variable name to make it a pointer:
</p>
{#code_begin|test|test_switch_modify_tagged_union#}
const std = @import("std");
const expect = std.testing.expect;
const ComplexTypeTag = enum {
ok,
not_ok,
};
const ComplexType = union(ComplexTypeTag) {
ok: u8,
not_ok: void,
};
test "modify tagged union in switch" {
var c = ComplexType{ .ok = 42 };
switch (c) {
ComplexTypeTag.ok => |*value| value.* += 1,
ComplexTypeTag.not_ok => unreachable,
}
try expect(c.ok == 43);
}
{#code_end#}
<p>
Unions can be made to infer the enum tag type.
Further, unions can have methods just like structs and enums.
</p>
{#code_begin|test|test_union_method#}
const std = @import("std");
const expect = std.testing.expect;
const Variant = union(enum) {
int: i32,
boolean: bool,
// void can be omitted when inferring enum tag type.
none,
fn truthy(self: Variant) bool {
return switch (self) {
Variant.int => |x_int| x_int != 0,
Variant.boolean => |x_bool| x_bool,
Variant.none => false,
};
}
};
test "union method" {
var v1 = Variant{ .int = 1 };
var v2 = Variant{ .boolean = false };
try expect(v1.truthy());
try expect(!v2.truthy());
}
{#code_end#}
<p>
{#link|@tagName#} can be used to return a {#link|comptime#}
{#syntax#}[:0]const u8{#endsyntax#} value representing the field name:
</p>
{#code_begin|test|test_tagName#}
const std = @import("std");
const expect = std.testing.expect;
const Small2 = union(enum) {
a: i32,
b: bool,
c: u8,
};
test "@tagName" {
try expect(std.mem.eql(u8, @tagName(Small2.a), "a"));
}
{#code_end#}
{#header_close#}
{#header_open|extern union#}
<p>
An {#syntax#}extern union{#endsyntax#} has memory layout guaranteed to be compatible with
the target C ABI.
</p>
{#see_also|extern struct#}
{#header_close#}
{#header_open|packed union#}
<p>A {#syntax#}packed union{#endsyntax#} has well-defined in-memory layout and is eligible
to be in a {#link|packed struct#}.</p>
{#header_close#}
{#header_open|Anonymous Union Literals#}
<p>{#link|Anonymous Struct Literals#} syntax can be used to initialize unions without specifying
the type:</p>
{#code_begin|test|test_anonymous_union#}
const std = @import("std");
const expect = std.testing.expect;
const Number = union {
int: i32,
float: f64,
};
test "anonymous union literal syntax" {
var i: Number = .{.int = 42};
var f = makeNumber();
try expect(i.int == 42);
try expect(f.float == 12.34);
}
fn makeNumber() Number {
return .{.float = 12.34};
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|opaque#}
<p>
{#syntax#}opaque {}{#endsyntax#} declares a new type with an unknown (but non-zero) size and alignment.
It can contain declarations the same as {#link|structs|struct#}, {#link|unions|union#},
and {#link|enums|enum#}.
</p>
<p>
This is typically used for type safety when interacting with C code that does not expose struct details.
Example:
</p>
{#code_begin|test_err|test_opaque|expected type '*test_opaque.Derp', found '*test_opaque.Wat'#}
const Derp = opaque {};
const Wat = opaque {};
extern fn bar(d: *Derp) void;
fn foo(w: *Wat) callconv(.C) void {
bar(w);
}
test "call foo" {
foo(undefined);
}
{#code_end#}
{#header_close#}
{#header_open|Blocks#}
<p>
Blocks are used to limit the scope of variable declarations:
</p>
{#code_begin|test_err|test_blocks|use of undeclared identifier 'x'#}
test "access variable after block scope" {
{
var x: i32 = 1;
_ = x;
}
x += 1;
}
{#code_end#}
<p>Blocks are expressions. When labeled, {#syntax#}break{#endsyntax#} can be used
to return a value from the block:
</p>
{#code_begin|test|test_labeled_break#}
const std = @import("std");
const expect = std.testing.expect;
test "labeled break from labeled block expression" {
var y: i32 = 123;
const x = blk: {
y += 1;
break :blk y;
};
try expect(x == 124);
try expect(y == 124);
}
{#code_end#}
<p>Here, {#syntax#}blk{#endsyntax#} can be any name.</p>
{#see_also|Labeled while|Labeled for#}
{#header_open|Shadowing#}
<p>{#link|Identifiers#} are never allowed to "hide" other identifiers by using the same name:</p>
{#code_begin|test_err|test_shadowing|local variable shadows declaration#}
const pi = 3.14;
test "inside test block" {
// Let's even go inside another block
{
var pi: i32 = 1234;
}
}
{#code_end#}
<p>
Because of this, when you read Zig code you can always rely on an identifier to consistently mean
the same thing within the scope it is defined. Note that you can, however, use the same name if
the scopes are separate:
</p>
{#code_begin|test|test_scopes#}
test "separate scopes" {
{
const pi = 3.14;
_ = pi;
}
{
var pi: bool = true;
_ = pi;
}
}
{#code_end#}
{#header_close#}
{#header_open|Empty Blocks#}
<p>An empty block is equivalent to {#syntax#}void{}{#endsyntax#}:</p>
{#code_begin|test|test_empty_block#}
const std = @import("std");
const expect = std.testing.expect;
test {
const a = {};
const b = void{};
try expect(@TypeOf(a) == void);
try expect(@TypeOf(b) == void);
try expect(a == b);
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|switch#}
{#code_begin|test|test_switch#}
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
test "switch simple" {
const a: u64 = 10;
const zz: u64 = 103;
// All branches of a switch expression must be able to be coerced to a
// common type.
//
// Branches cannot fallthrough. If fallthrough behavior is desired, combine
// the cases and use an if.
const b = switch (a) {
// Multiple cases can be combined via a ','
1, 2, 3 => 0,
// Ranges can be specified using the ... syntax. These are inclusive
// of both ends.
5...100 => 1,
// Branches can be arbitrarily complex.
101 => blk: {
const c: u64 = 5;
break :blk c * 2 + 1;
},
// Switching on arbitrary expressions is allowed as long as the
// expression is known at compile-time.
zz => zz,
blk: {
const d: u32 = 5;
const e: u32 = 100;
break :blk d + e;
} => 107,
// The else branch catches everything not already captured.
// Else branches are mandatory unless the entire range of values
// is handled.
else => 9,
};
try expect(b == 1);
}
// Switch expressions can be used outside a function:
const os_msg = switch (builtin.target.os.tag) {
.linux => "we found a linux user",
else => "not a linux user",
};
// Inside a function, switch statements implicitly are compile-time
// evaluated if the target expression is compile-time known.
test "switch inside function" {
switch (builtin.target.os.tag) {
.fuchsia => {
// On an OS other than fuchsia, block is not even analyzed,
// so this compile error is not triggered.
// On fuchsia this compile error would be triggered.
@compileError("fuchsia not supported");
},
else => {},
}
}
{#code_end#}
<p>
{#syntax#}switch{#endsyntax#} can be used to capture the field values
of a {#link|Tagged union#}. Modifications to the field values can be
done by placing a {#syntax#}*{#endsyntax#} before the capture variable name,
turning it into a pointer.
</p>
{#code_begin|test|test_switch_tagged_union#}
const expect = @import("std").testing.expect;
test "switch on tagged union" {
const Point = struct {
x: u8,
y: u8,
};
const Item = union(enum) {
a: u32,
c: Point,
d,
e: u32,
};
var a = Item{ .c = Point{ .x = 1, .y = 2 } };
// Switching on more complex enums is allowed.
const b = switch (a) {
// A capture group is allowed on a match, and will return the enum
// value matched. If the payload types of both cases are the same
// they can be put into the same switch prong.
Item.a, Item.e => |item| item,
// A reference to the matched value can be obtained using `*` syntax.
Item.c => |*item| blk: {
item.*.x += 1;
break :blk 6;
},
// No else is required if the types cases was exhaustively handled
Item.d => 8,
};
try expect(b == 6);
try expect(a.c.x == 2);
}
{#code_end#}
{#see_also|comptime|enum|@compileError|Compile Variables#}
{#header_open|Exhaustive Switching#}
<p>
When a {#syntax#}switch{#endsyntax#} expression does not have an {#syntax#}else{#endsyntax#} clause,
it must exhaustively list all the possible values. Failure to do so is a compile error:
</p>
{#code_begin|test_err|test_unhandled_enumeration_value|unhandled enumeration value#}
const Color = enum {
auto,
off,
on,
};
test "exhaustive switching" {
const color = Color.off;
switch (color) {
Color.auto => {},
Color.on => {},
}
}
{#code_end#}
{#header_close#}
{#header_open|Switching with Enum Literals#}
<p>
{#link|Enum Literals#} can be useful to use with {#syntax#}switch{#endsyntax#} to avoid
repetitively specifying {#link|enum#} or {#link|union#} types:
</p>
{#code_begin|test|test_exhaustive_switch#}
const std = @import("std");
const expect = std.testing.expect;
const Color = enum {
auto,
off,
on,
};
test "enum literals with switch" {
const color = Color.off;
const result = switch (color) {
.auto => false,
.on => false,
.off => true,
};
try expect(result);
}
{#code_end#}
{#header_close#}
{#header_open|Inline switch#}
<p>
Switch prongs can be marked as {#syntax#}inline{#endsyntax#} to generate
the prong's body for each possible value it could have:
</p>
{#code_begin|test|test_inline_switch#}
const std = @import("std");
const expect = std.testing.expect;
const expectError = std.testing.expectError;
fn isFieldOptional(comptime T: type, field_index: usize) !bool {
const fields = @typeInfo(T).Struct.fields;
return switch (field_index) {
// This prong is analyzed `fields.len - 1` times with `idx` being an
// unique comptime-known value each time.
inline 0...fields.len - 1 => |idx| @typeInfo(fields[idx].type) == .Optional,
else => return error.IndexOutOfBounds,
};
}
const Struct1 = struct { a: u32, b: ?u32 };
test "using @typeInfo with runtime values" {
var index: usize = 0;
try expect(!try isFieldOptional(Struct1, index));
index += 1;
try expect(try isFieldOptional(Struct1, index));
index += 1;
try expectError(error.IndexOutOfBounds, isFieldOptional(Struct1, index));
}
// Calls to `isFieldOptional` on `Struct1` get unrolled to an equivalent
// of this function:
fn isFieldOptionalUnrolled(field_index: usize) !bool {
return switch (field_index) {
0 => false,
1 => true,
else => return error.IndexOutOfBounds,
};
}
{#code_end#}
<p>
{#syntax#}inline else{#endsyntax#} prongs can be used as a type safe
alternative to {#syntax#}inline for{#endsyntax#} loops:
</p>
{#code_begin|test|test_inline_else#}
const std = @import("std");
const expect = std.testing.expect;
const SliceTypeA = extern struct {
len: usize,
ptr: [*]u32,
};
const SliceTypeB = extern struct {
ptr: [*]SliceTypeA,
len: usize,
};
const AnySlice = union(enum) {
a: SliceTypeA,
b: SliceTypeB,
c: []const u8,
d: []AnySlice,
};
fn withFor(any: AnySlice) usize {
const Tag = @typeInfo(AnySlice).Union.tag_type.?;
inline for (@typeInfo(Tag).Enum.fields) |field| {
// With `inline for` the function gets generated as
// a series of `if` statements relying on the optimizer
// to convert it to a switch.
if (field.value == @enumToInt(any)) {
return @field(any, field.name).len;
}
}
// When using `inline for` the compiler doesn't know that every
// possible case has been handled requiring an explicit `unreachable`.
unreachable;
}
fn withSwitch(any: AnySlice) usize {
return switch (any) {
// With `inline else` the function is explicitly generated
// as the desired switch and the compiler can check that
// every possible case is handled.
inline else => |slice| slice.len,
};
}
test "inline for and inline else similarity" {
var any = AnySlice{ .c = "hello" };
try expect(withFor(any) == 5);
try expect(withSwitch(any) == 5);
}
{#code_end#}
<p>
When using an inline prong switching on an union an additional
capture can be used to obtain the union's enum tag value.
</p>
{#code_begin|test|test_inline_switch_union_tag#}
const std = @import("std");
const expect = std.testing.expect;
const U = union(enum) {
a: u32,
b: f32,
};
fn getNum(u: U) u32 {
switch (u) {
// Here `num` is a runtime-known value that is either
// `u.a` or `u.b` and `tag` is `u`'s comptime-known tag value.
inline else => |num, tag| {
if (tag == .b) {
return @floatToInt(u32, num);
}
return num;
}
}
}
test "test" {
var u = U{ .b = 42 };
try expect(getNum(u) == 42);
}
{#code_end#}
{#see_also|inline while|inline for#}
{#header_close#}
{#header_close#}
{#header_open|while#}
<p>
A while loop is used to repeatedly execute an expression until
some condition is no longer true.
</p>
{#code_begin|test|test_while#}
const expect = @import("std").testing.expect;
test "while basic" {
var i: usize = 0;
while (i < 10) {
i += 1;
}
try expect(i == 10);
}
{#code_end#}
<p>
Use {#syntax#}break{#endsyntax#} to exit a while loop early.
</p>
{#code_begin|test|test_while_break#}
const expect = @import("std").testing.expect;
test "while break" {
var i: usize = 0;
while (true) {
if (i == 10)
break;
i += 1;
}
try expect(i == 10);
}
{#code_end#}
<p>
Use {#syntax#}continue{#endsyntax#} to jump back to the beginning of the loop.
</p>
{#code_begin|test|test_while_continue#}
const expect = @import("std").testing.expect;
test "while continue" {
var i: usize = 0;
while (true) {
i += 1;
if (i < 10)
continue;
break;
}
try expect(i == 10);
}
{#code_end#}
<p>
While loops support a continue expression which is executed when the loop
is continued. The {#syntax#}continue{#endsyntax#} keyword respects this expression.
</p>
{#code_begin|test|test_while_continue_expression#}
const expect = @import("std").testing.expect;
test "while loop continue expression" {
var i: usize = 0;
while (i < 10) : (i += 1) {}
try expect(i == 10);
}
test "while loop continue expression, more complicated" {
var i: usize = 1;
var j: usize = 1;
while (i * j < 2000) : ({ i *= 2; j *= 3; }) {
const my_ij = i * j;
try expect(my_ij < 2000);
}
}
{#code_end#}
<p>
While loops are expressions. The result of the expression is the
result of the {#syntax#}else{#endsyntax#} clause of a while loop, which is executed when
the condition of the while loop is tested as false.
</p>
<p>
{#syntax#}break{#endsyntax#}, like {#syntax#}return{#endsyntax#}, accepts a value
parameter. This is the result of the {#syntax#}while{#endsyntax#} expression.
When you {#syntax#}break{#endsyntax#} from a while loop, the {#syntax#}else{#endsyntax#} branch is not
evaluated.
</p>
{#code_begin|test|test_while_else#}
const expect = @import("std").testing.expect;
test "while else" {
try expect(rangeHasNumber(0, 10, 5));
try expect(!rangeHasNumber(0, 10, 15));
}
fn rangeHasNumber(begin: usize, end: usize, number: usize) bool {
var i = begin;
return while (i < end) : (i += 1) {
if (i == number) {
break true;
}
} else false;
}
{#code_end#}
{#header_open|Labeled while#}
<p>When a {#syntax#}while{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#}
or {#syntax#}continue{#endsyntax#} from within a nested loop:</p>
{#code_begin|test|test_while_nested_break#}
test "nested break" {
outer: while (true) {
while (true) {
break :outer;
}
}
}
test "nested continue" {
var i: usize = 0;
outer: while (i < 10) : (i += 1) {
while (true) {
continue :outer;
}
}
}
{#code_end#}
{#header_close#}
{#header_open|while with Optionals#}
<p>
Just like {#link|if#} expressions, while loops can take an optional as the
condition and capture the payload. When {#link|null#} is encountered the loop
exits.
</p>
<p>
When the {#syntax#}|x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression,
the while condition must have an {#link|Optional Type#}.
</p>
<p>
The {#syntax#}else{#endsyntax#} branch is allowed on optional iteration. In this case, it will
be executed on the first null value encountered.
</p>
{#code_begin|test|test_while_null_capture#}
const expect = @import("std").testing.expect;
test "while null capture" {
var sum1: u32 = 0;
numbers_left = 3;
while (eventuallyNullSequence()) |value| {
sum1 += value;
}
try expect(sum1 == 3);
var sum2: u32 = 0;
numbers_left = 3;
while (eventuallyNullSequence()) |value| {
sum2 += value;
} else {
try expect(sum2 == 3);
}
}
var numbers_left: u32 = undefined;
fn eventuallyNullSequence() ?u32 {
return if (numbers_left == 0) null else blk: {
numbers_left -= 1;
break :blk numbers_left;
};
}
{#code_end#}
{#header_close#}
{#header_open|while with Error Unions#}
<p>
Just like {#link|if#} expressions, while loops can take an error union as
the condition and capture the payload or the error code. When the
condition results in an error code the else branch is evaluated and
the loop is finished.
</p>
<p>
When the {#syntax#}else |x|{#endsyntax#} syntax is present on a {#syntax#}while{#endsyntax#} expression,
the while condition must have an {#link|Error Union Type#}.
</p>
{#code_begin|test|test_while_error_capture#}
const expect = @import("std").testing.expect;
test "while error union capture" {
var sum1: u32 = 0;
numbers_left = 3;
while (eventuallyErrorSequence()) |value| {
sum1 += value;
} else |err| {
try expect(err == error.ReachedZero);
}
}
var numbers_left: u32 = undefined;
fn eventuallyErrorSequence() anyerror!u32 {
return if (numbers_left == 0) error.ReachedZero else blk: {
numbers_left -= 1;
break :blk numbers_left;
};
}
{#code_end#}
{#header_close#}
{#header_open|inline while#}
<p>
While loops can be inlined. This causes the loop to be unrolled, which
allows the code to do some things which only work at compile time,
such as use types as first class values.
</p>
{#code_begin|test|test_inline_while#}
const expect = @import("std").testing.expect;
test "inline while loop" {
comptime var i = 0;
var sum: usize = 0;
inline while (i < 3) : (i += 1) {
const T = switch (i) {
0 => f32,
1 => i8,
2 => bool,
else => unreachable,
};
sum += typeNameLength(T);
}
try expect(sum == 9);
}
fn typeNameLength(comptime T: type) usize {
return @typeName(T).len;
}
{#code_end#}
<p>
It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons:
</p>
<ul>
<li>You need the loop to execute at {#link|comptime#} for the semantics to work.</li>
<li>
You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster.
</li>
</ul>
{#header_close#}
{#see_also|if|Optionals|Errors|comptime|unreachable#}
{#header_close#}
{#header_open|for#}
{#code_begin|test|test_for#}
const expect = @import("std").testing.expect;
test "for basics" {
const items = [_]i32 { 4, 5, 3, 4, 0 };
var sum: i32 = 0;
// For loops iterate over slices and arrays.
for (items) |value| {
// Break and continue are supported.
if (value == 0) {
continue;
}
sum += value;
}
try expect(sum == 16);
// To iterate over a portion of a slice, reslice.
for (items[0..1]) |value| {
sum += value;
}
try expect(sum == 20);
// To access the index of iteration, specify a second capture value.
// This is zero-indexed.
var sum2: i32 = 0;
for (items) |_, i| {
try expect(@TypeOf(i) == usize);
sum2 += @intCast(i32, i);
}
try expect(sum2 == 10);
}
test "for reference" {
var items = [_]i32 { 3, 4, 2 };
// Iterate over the slice by reference by
// specifying that the capture value is a pointer.
for (items) |*value| {
value.* += 1;
}
try expect(items[0] == 4);
try expect(items[1] == 5);
try expect(items[2] == 3);
}
test "for else" {
// For allows an else attached to it, the same as a while loop.
var items = [_]?i32 { 3, 4, null, 5 };
// For loops can also be used as expressions.
// Similar to while loops, when you break from a for loop, the else branch is not evaluated.
var sum: i32 = 0;
const result = for (items) |value| {
if (value != null) {
sum += value.?;
}
} else blk: {
try expect(sum == 12);
break :blk sum;
};
try expect(result == 12);
}
{#code_end#}
{#header_open|Labeled for#}
<p>When a {#syntax#}for{#endsyntax#} loop is labeled, it can be referenced from a {#syntax#}break{#endsyntax#}
or {#syntax#}continue{#endsyntax#} from within a nested loop:</p>
{#code_begin|test|test_for_nested_break#}
const std = @import("std");
const expect = std.testing.expect;
test "nested break" {
var count: usize = 0;
outer: for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
count += 1;
break :outer;
}
}
try expect(count == 1);
}
test "nested continue" {
var count: usize = 0;
outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {
for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
count += 1;
continue :outer;
}
}
try expect(count == 8);
}
{#code_end#}
{#header_close#}
{#header_open|inline for#}
<p>
For loops can be inlined. This causes the loop to be unrolled, which
allows the code to do some things which only work at compile time,
such as use types as first class values.
The capture value and iterator value of inlined for loops are
compile-time known.
</p>
{#code_begin|test|test_inline_for#}
const expect = @import("std").testing.expect;
test "inline for loop" {
const nums = [_]i32{2, 4, 6};
var sum: usize = 0;
inline for (nums) |i| {
const T = switch (i) {
2 => f32,
4 => i8,
6 => bool,
else => unreachable,
};
sum += typeNameLength(T);
}
try expect(sum == 9);
}
fn typeNameLength(comptime T: type) usize {
return @typeName(T).len;
}
{#code_end#}
<p>
It is recommended to use {#syntax#}inline{#endsyntax#} loops only for one of these reasons:
</p>
<ul>
<li>You need the loop to execute at {#link|comptime#} for the semantics to work.</li>
<li>
You have a benchmark to prove that forcibly unrolling the loop in this way is measurably faster.
</li>
</ul>
{#header_close#}
{#see_also|while|comptime|Arrays|Slices#}
{#header_close#}
{#header_open|if#}
{#code_begin|test|test_if#}
// If expressions have three uses, corresponding to the three types:
// * bool
// * ?T
// * anyerror!T
const expect = @import("std").testing.expect;
test "if expression" {
// If expressions are used instead of a ternary expression.
const a: u32 = 5;
const b: u32 = 4;
const result = if (a != b) 47 else 3089;
try expect(result == 47);
}
test "if boolean" {
// If expressions test boolean conditions.
const a: u32 = 5;
const b: u32 = 4;
if (a != b) {
try expect(true);
} else if (a == 9) {
unreachable;
} else {
unreachable;
}
}
test "if optional" {
// If expressions test for null.
const a: ?u32 = 0;
if (a) |value| {
try expect(value == 0);
} else {
unreachable;
}
const b: ?u32 = null;
if (b) |_| {
unreachable;
} else {
try expect(true);
}
// The else is not required.
if (a) |value| {
try expect(value == 0);
}
// To test against null only, use the binary equality operator.
if (b == null) {
try expect(true);
}
// Access the value by reference using a pointer capture.
var c: ?u32 = 3;
if (c) |*value| {
value.* = 2;
}
if (c) |value| {
try expect(value == 2);
} else {
unreachable;
}
}
test "if error union" {
// If expressions test for errors.
// Note the |err| capture on the else.
const a: anyerror!u32 = 0;
if (a) |value| {
try expect(value == 0);
} else |err| {
_ = err;
unreachable;
}
const b: anyerror!u32 = error.BadValue;
if (b) |value| {
_ = value;
unreachable;
} else |err| {
try expect(err == error.BadValue);
}
// The else and |err| capture is strictly required.
if (a) |value| {
try expect(value == 0);
} else |_| {}
// To check only the error value, use an empty block expression.
if (b) |_| {} else |err| {
try expect(err == error.BadValue);
}
// Access the value by reference using a pointer capture.
var c: anyerror!u32 = 3;
if (c) |*value| {
value.* = 9;
} else |_| {
unreachable;
}
if (c) |value| {
try expect(value == 9);
} else |_| {
unreachable;
}
}
test "if error union with optional" {
// If expressions test for errors before unwrapping optionals.
// The |optional_value| capture's type is ?u32.
const a: anyerror!?u32 = 0;
if (a) |optional_value| {
try expect(optional_value.? == 0);
} else |err| {
_ = err;
unreachable;
}
const b: anyerror!?u32 = null;
if (b) |optional_value| {
try expect(optional_value == null);
} else |_| {
unreachable;
}
const c: anyerror!?u32 = error.BadValue;
if (c) |optional_value| {
_ = optional_value;
unreachable;
} else |err| {
try expect(err == error.BadValue);
}
// Access the value by reference by using a pointer capture each time.
var d: anyerror!?u32 = 3;
if (d) |*optional_value| {
if (optional_value.*) |*value| {
value.* = 9;
}
} else |_| {
unreachable;
}
if (d) |optional_value| {
try expect(optional_value.? == 9);
} else |_| {
unreachable;
}
}
{#code_end#}
{#see_also|Optionals|Errors#}
{#header_close#}
{#header_open|defer#}
{#code_begin|test|test_defer#}
const std = @import("std");
const expect = std.testing.expect;
const print = std.debug.print;
// defer will execute an expression at the end of the current scope.
fn deferExample() !usize {
var a: usize = 1;
{
defer a = 2;
a = 1;
}
try expect(a == 2);
a = 5;
return a;
}
test "defer basics" {
try expect((try deferExample()) == 5);
}
// If multiple defer statements are specified, they will be executed in
// the reverse order they were run.
fn deferUnwindExample() void {
print("\n", .{});
defer {
print("1 ", .{});
}
defer {
print("2 ", .{});
}
if (false) {
// defers are not run if they are never executed.
defer {
print("3 ", .{});
}
}
}
test "defer unwinding" {
deferUnwindExample();
}
{#code_end#}
{#code_begin|test_err|test_invalid_defer|cannot return from defer expression#}
// Inside a defer expression the return statement is not allowed.
fn deferInvalidExample() !void {
defer {
return error.DeferError;
}
return error.DeferError;
}
{#code_end#}
{#code_begin|test|test_errdefer#}
const std = @import("std");
const print = std.debug.print;
// The errdefer keyword is similar to defer, but will only execute if the
// scope returns with an error.
//
// This is especially useful in allowing a function to clean up properly
// on error, and replaces goto error handling tactics as seen in c.
fn deferErrorExample(is_error: bool) !void {
print("\nstart of function\n", .{});
// This will always be executed on exit
defer {
print("end of function\n", .{});
}
errdefer {
print("encountered an error!\n", .{});
}
if (is_error) {
return error.DeferError;
}
}
// The errdefer keyword support also an alternative syntax to capture the
// error generated in case of one error.
//
// This is useful when during the clean up after an error additional
// message want to be printed.
fn deferErrorCaptureExample() !void {
errdefer |err| {
std.debug.print("the error is {s}\n", .{@errorName(err)});
}
return error.DeferError;
}
test "errdefer unwinding" {
deferErrorExample(false) catch {};
deferErrorExample(true) catch {};
deferErrorCaptureExample() catch {};
}
{#code_end#}
{#see_also|Errors#}
{#header_close#}
{#header_open|unreachable#}
<p>
In {#link|Debug#} and {#link|ReleaseSafe#} mode
{#syntax#}unreachable{#endsyntax#} emits a call to {#syntax#}panic{#endsyntax#} with the message <code>reached unreachable code</code>.
</p>
<p>
In {#link|ReleaseFast#} and {#link|ReleaseSmall#} mode, the optimizer uses the assumption that {#syntax#}unreachable{#endsyntax#} code
will never be hit to perform optimizations.
</p>
{#header_open|Basics#}
{#code_begin|test|test_unreachable#}
// unreachable is used to assert that control flow will never reach a
// particular location:
test "basic math" {
const x = 1;
const y = 2;
if (x + y != 3) {
unreachable;
}
}
{#code_end#}
<p>In fact, this is how {#syntax#}std.debug.assert{#endsyntax#} is implemented:</p>
{#code_begin|test_err|test_assertion_failure#}
// This is how std.debug.assert is implemented
fn assert(ok: bool) void {
if (!ok) unreachable; // assertion failure
}
// This test will fail because we hit unreachable.
test "this will fail" {
assert(false);
}
{#code_end#}
{#header_close#}
{#header_open|At Compile-Time#}
{#code_begin|test_err|test_comptime_unreachable|unreachable code#}
const assert = @import("std").debug.assert;
test "type of unreachable" {
comptime {
// The type of unreachable is noreturn.
// However this assertion will still fail to compile because
// unreachable expressions are compile errors.
assert(@TypeOf(unreachable) == noreturn);
}
}
{#code_end#}
{#see_also|Zig Test|Build Mode|comptime#}
{#header_close#}
{#header_close#}
{#header_open|noreturn#}
<p>
{#syntax#}noreturn{#endsyntax#} is the type of:
</p>
<ul>
<li>{#syntax#}break{#endsyntax#}</li>
<li>{#syntax#}continue{#endsyntax#}</li>
<li>{#syntax#}return{#endsyntax#}</li>
<li>{#syntax#}unreachable{#endsyntax#}</li>
<li>{#syntax#}while (true) {}{#endsyntax#}</li>
</ul>
<p>When resolving types together, such as {#syntax#}if{#endsyntax#} clauses or {#syntax#}switch{#endsyntax#} prongs,
the {#syntax#}noreturn{#endsyntax#} type is compatible with every other type. Consider:
</p>
{#code_begin|test|test_noreturn#}
fn foo(condition: bool, b: u32) void {
const a = if (condition) b else return;
_ = a;
@panic("do something with a");
}
test "noreturn" {
foo(false, 1);
}
{#code_end#}
<p>Another use case for {#syntax#}noreturn{#endsyntax#} is the {#syntax#}exit{#endsyntax#} function:</p>
{#code_begin|test|test_noreturn_from_exit#}
{#target_windows#}
const std = @import("std");
const builtin = @import("builtin");
const native_arch = builtin.cpu.arch;
const expect = std.testing.expect;
const WINAPI: std.builtin.CallingConvention = if (native_arch == .x86) .Stdcall else .C;
extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(WINAPI) noreturn;
test "foo" {
const value = bar() catch ExitProcess(1);
try expect(value == 1234);
}
fn bar() anyerror!u32 {
return 1234;
}
{#code_end#}
{#header_close#}
{#header_open|Functions#}
{#code_begin|test|test_functions#}
const std = @import("std");
const builtin = @import("builtin");
const native_arch = builtin.cpu.arch;
const expect = std.testing.expect;
// Functions are declared like this
fn add(a: i8, b: i8) i8 {
if (a == 0) {
return b;
}
return a + b;
}
// The export specifier makes a function externally visible in the generated
// object file, and makes it use the C ABI.
export fn sub(a: i8, b: i8) i8 { return a - b; }
// The extern specifier is used to declare a function that will be resolved
// at link time, when linking statically, or at runtime, when linking
// dynamically.
// The callconv specifier changes the calling convention of the function.
const WINAPI: std.builtin.CallingConvention = if (native_arch == .x86) .Stdcall else .C;
extern "kernel32" fn ExitProcess(exit_code: u32) callconv(WINAPI) noreturn;
extern "c" fn atan2(a: f64, b: f64) f64;
// The @setCold builtin tells the optimizer that a function is rarely called.
fn abort() noreturn {
@setCold(true);
while (true) {}
}
// The naked calling convention makes a function not have any function prologue or epilogue.
// This can be useful when integrating with assembly.
fn _start() callconv(.Naked) noreturn {
abort();
}
// The inline calling convention forces a function to be inlined at all call sites.
// If the function cannot be inlined, it is a compile-time error.
fn shiftLeftOne(a: u32) callconv(.Inline) u32 {
return a << 1;
}
// The pub specifier allows the function to be visible when importing.
// Another file can use @import and call sub2
pub fn sub2(a: i8, b: i8) i8 { return a - b; }
// Function pointers are prefixed with `*const `.
const call2_op = *const fn (a: i8, b: i8) i8;
fn do_op(fn_call: call2_op, op1: i8, op2: i8) i8 {
return fn_call(op1, op2);
}
test "function" {
try expect(do_op(add, 5, 6) == 11);
try expect(do_op(sub2, 5, 6) == -1);
}
{#code_end#}
<p>There is a difference between a function <em>body</em> and a function <em>pointer</em>.
Function bodies are {#link|comptime#}-only types while function {#link|Pointers#} may be
runtime-known.</p>
{#header_open|Pass-by-value Parameters#}
<p>
Primitive types such as {#link|Integers#} and {#link|Floats#} passed as parameters
are copied, and then the copy is available in the function body. This is called "passing by value".
Copying a primitive type is essentially free and typically involves nothing more than
setting a register.
</p>
<p>
Structs, unions, and arrays can sometimes be more efficiently passed as a reference, since a copy
could be arbitrarily expensive depending on the size. When these types are passed
as parameters, Zig may choose to copy and pass by value, or pass by reference, whichever way
Zig decides will be faster. This is made possible, in part, by the fact that parameters are immutable.
</p>
{#code_begin|test|test_pass_by_reference_or_value#}
const Point = struct {
x: i32,
y: i32,
};
fn foo(point: Point) i32 {
// Here, `point` could be a reference, or a copy. The function body
// can ignore the difference and treat it as a value. Be very careful
// taking the address of the parameter - it should be treated as if
// the address will become invalid when the function returns.
return point.x + point.y;
}
const expect = @import("std").testing.expect;
test "pass struct to function" {
try expect(foo(Point{ .x = 1, .y = 2 }) == 3);
}
{#code_end#}
<p>
For extern functions, Zig follows the C ABI for passing structs and unions by value.
</p>
{#header_close#}
{#header_open|Function Parameter Type Inference#}
<p>
Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type.
In this case the parameter types will be inferred when the function is called.
Use {#link|@TypeOf#} and {#link|@typeInfo#} to get information about the inferred type.
</p>
{#code_begin|test|test_fn_type_inference#}
const expect = @import("std").testing.expect;
fn addFortyTwo(x: anytype) @TypeOf(x) {
return x + 42;
}
test "fn type inference" {
try expect(addFortyTwo(1) == 43);
try expect(@TypeOf(addFortyTwo(1)) == comptime_int);
var y: i64 = 2;
try expect(addFortyTwo(y) == 44);
try expect(@TypeOf(addFortyTwo(y)) == i64);
}
{#code_end#}
{#header_close#}
{#header_open|Function Reflection#}
{#code_begin|test|test_fn_reflection#}
const std = @import("std");
const math = std.math;
const testing = std.testing;
test "fn reflection" {
try testing.expect(@typeInfo(@TypeOf(testing.expect)).Fn.params[0].type.? == bool);
try testing.expect(@typeInfo(@TypeOf(testing.tmpDir)).Fn.return_type.? == testing.TmpDir);
try testing.expect(@typeInfo(@TypeOf(math.Log2Int)).Fn.is_generic);
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Errors#}
{#header_open|Error Set Type#}
<p>
An error set is like an {#link|enum#}.
However, each error name across the entire compilation gets assigned an unsigned integer
greater than 0. You are allowed to declare the same error name more than once, and if you do, it
gets assigned the same integer value.
</p>
<p>
The number of unique error values across the entire compilation should determine the size of the error set type.
However right now it is hard coded to be a {#syntax#}u16{#endsyntax#}. See <a href="https://github.com/ziglang/zig/issues/786">#768</a>.
</p>
<p>
You can {#link|coerce|Type Coercion#} an error from a subset to a superset:
</p>
{#code_begin|test|test_coerce_error_subset_to_superset#}
const std = @import("std");
const FileOpenError = error {
AccessDenied,
OutOfMemory,
FileNotFound,
};
const AllocationError = error {
OutOfMemory,
};
test "coerce subset to superset" {
const err = foo(AllocationError.OutOfMemory);
try std.testing.expect(err == FileOpenError.OutOfMemory);
}
fn foo(err: AllocationError) FileOpenError {
return err;
}
{#code_end#}
<p>
But you cannot {#link|coerce|Type Coercion#} an error from a superset to a subset:
</p>
{#code_begin|test_err|test_coerce_error_superset_to_subset|not a member of destination error set#}
const FileOpenError = error {
AccessDenied,
OutOfMemory,
FileNotFound,
};
const AllocationError = error {
OutOfMemory,
};
test "coerce superset to subset" {
foo(FileOpenError.OutOfMemory) catch {};
}
fn foo(err: FileOpenError) AllocationError {
return err;
}
{#code_end#}
<p>
There is a shortcut for declaring an error set with only 1 value, and then getting that value:
</p>
{#code_begin|syntax|single_value_error_set_shortcut#}
const err = error.FileNotFound;
{#code_end#}
<p>This is equivalent to:</p>
{#code_begin|syntax|single_value_error_set#}
const err = (error {FileNotFound}).FileNotFound;
{#code_end#}
<p>
This becomes useful when using {#link|Inferred Error Sets#}.
</p>
{#header_open|The Global Error Set#}
<p>{#syntax#}anyerror{#endsyntax#} refers to the global error set.
This is the error set that contains all errors in the entire compilation unit.
It is a superset of all other error sets and a subset of none of them.
</p>
<p>
You can {#link|coerce|Type Coercion#} any error set to the global one, and you can explicitly
cast an error of the global error set to a non-global one. This inserts a language-level
assert to make sure the error value is in fact in the destination error set.
</p>
<p>
The global error set should generally be avoided because it prevents the
compiler from knowing what errors are possible at compile-time. Knowing
the error set at compile-time is better for generated documentation and
helpful error messages, such as forgetting a possible error value in a {#link|switch#}.
</p>
{#header_close#}
{#header_close#}
{#header_open|Error Union Type#}
<p>
An error set type and normal type can be combined with the {#syntax#}!{#endsyntax#}
binary operator to form an error union type. You are likely to use an
error union type more often than an error set type by itself.
</p>
<p>
Here is a function to parse a string into a 64-bit integer:
</p>
{#code_begin|test|error_union_parsing_u64#}
const std = @import("std");
const maxInt = std.math.maxInt;
pub fn parseU64(buf: []const u8, radix: u8) !u64 {
var x: u64 = 0;
for (buf) |c| {
const digit = charToDigit(c);
if (digit >= radix) {
return error.InvalidChar;
}
// x *= radix
var ov = @mulWithOverflow(x, radix);
if (ov[1] != 0) return error.OverFlow;
// x += digit
ov = @addWithOverflow(ov[0], digit);
if (ov[1] != 0) return error.OverFlow;
x = ov[0];
}
return x;
}
fn charToDigit(c: u8) u8 {
return switch (c) {
'0' ... '9' => c - '0',
'A' ... 'Z' => c - 'A' + 10,
'a' ... 'z' => c - 'a' + 10,
else => maxInt(u8),
};
}
test "parse u64" {
const result = try parseU64("1234", 10);
try std.testing.expect(result == 1234);
}
{#code_end#}
<p>
Notice the return type is {#syntax#}!u64{#endsyntax#}. This means that the function
either returns an unsigned 64 bit integer, or an error. We left off the error set
to the left of the {#syntax#}!{#endsyntax#}, so the error set is inferred.
</p>
<p>
Within the function definition, you can see some return statements that return
an error, and at the bottom a return statement that returns a {#syntax#}u64{#endsyntax#}.
Both types {#link|coerce|Type Coercion#} to {#syntax#}anyerror!u64{#endsyntax#}.
</p>
<p>
What it looks like to use this function varies depending on what you're
trying to do. One of the following:
</p>
<ul>
<li>You want to provide a default value if it returned an error.</li>
<li>If it returned an error then you want to return the same error.</li>
<li>You know with complete certainty it will not return an error, so want to unconditionally unwrap it.</li>
<li>You want to take a different action for each possible error.</li>
</ul>
{#header_open|catch#}
<p>If you want to provide a default value, you can use the {#syntax#}catch{#endsyntax#} binary operator:</p>
{#code_begin|syntax|catch#}
const parseU64 = @import("error_union_parsing_u64.zig").parseU64;
fn doAThing(str: []u8) void {
const number = parseU64(str, 10) catch 13;
_ = number; // ...
}
{#code_end#}
<p>
In this code, {#syntax#}number{#endsyntax#} will be equal to the successfully parsed string, or
a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must
match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}.
</p>
{#header_close#}
{#header_open|try#}
<p>Let's say you wanted to return the error if you got one, otherwise continue with the
function logic:</p>
{#code_begin|syntax|catch_err_return#}
const parseU64 = @import("error_union_parsing_u64.zig").parseU64;
fn doAThing(str: []u8) !void {
const number = parseU64(str, 10) catch |err| return err;
_ = number; // ...
}
{#code_end#}
<p>
There is a shortcut for this. The {#syntax#}try{#endsyntax#} expression:
</p>
{#code_begin|syntax|try#}
const parseU64 = @import("error_union_parsing_u64.zig").parseU64;
fn doAThing(str: []u8) !void {
const number = try parseU64(str, 10);
_ = number; // ...
}
{#code_end#}
<p>
{#syntax#}try{#endsyntax#} evaluates an error union expression. If it is an error, it returns
from the current function with the same error. Otherwise, the expression results in
the unwrapped value.
</p>
{#header_close#}
<p>
Maybe you know with complete certainty that an expression will never be an error.
In this case you can do this:
</p>
{#syntax#}const number = parseU64("1234", 10) catch unreachable;{#endsyntax#}
<p>
Here we know for sure that "1234" will parse successfully. So we put the
{#syntax#}unreachable{#endsyntax#} value on the right hand side. {#syntax#}unreachable{#endsyntax#} generates
a panic in {#link|Debug#} and {#link|ReleaseSafe#} modes and undefined behavior in
{#link|ReleaseFast#} and {#link|ReleaseSmall#} modes. So, while we're debugging the
application, if there <em>was</em> a surprise error here, the application would crash
appropriately.
</p>
<p>
Finally, you may want to take a different action for every situation. For that, we combine
the {#link|if#} and {#link|switch#} expression:
</p>
{#syntax_block|zig|handle_all_error_scenarios.zig#}
fn doAThing(str: []u8) void {
if (parseU64(str, 10)) |number| {
doSomethingWithNumber(number);
} else |err| switch (err) {
error.Overflow => {
// handle overflow...
},
// we promise that InvalidChar won't happen (or crash in debug mode if it does)
error.InvalidChar => unreachable,
}
}
{#end_syntax_block#}
{#header_open|errdefer#}
<p>
The other component to error handling is defer statements.
In addition to an unconditional {#link|defer#}, Zig has {#syntax#}errdefer{#endsyntax#},
which evaluates the deferred expression on block exit path if and only if
the function returned with an error from the block.
</p>
<p>
Example:
</p>
{#syntax_block|zig|errdefer_example.zig#}
fn createFoo(param: i32) !Foo {
const foo = try tryToAllocateFoo();
// now we have allocated foo. we need to free it if the function fails.
// but we want to return it if the function succeeds.
errdefer deallocateFoo(foo);
const tmp_buf = allocateTmpBuffer() orelse return error.OutOfMemory;
// tmp_buf is truly a temporary resource, and we for sure want to clean it up
// before this block leaves scope
defer deallocateTmpBuffer(tmp_buf);
if (param > 1337) return error.InvalidParam;
// here the errdefer will not run since we're returning success from the function.
// but the defer will run!
return foo;
}
{#end_syntax_block#}
<p>
The neat thing about this is that you get robust error handling without
the verbosity and cognitive overhead of trying to make sure every exit path
is covered. The deallocation code is always directly following the allocation code.
</p>
{#header_close#}
{#header_open|Common errdefer Slip-Ups#}
<p>
It should be noted that {#syntax#}errdefer{#endsyntax#} statements only last until the end of the block
they are written in, and therefore are not run if an error is returned outside of that block:
</p>
{#code_begin|test_err|test_errdefer_slip_ups|1 tests leaked memory#}
const std = @import("std");
const Allocator = std.mem.Allocator;
const Foo = struct {
data: u32,
};
fn tryToAllocateFoo(allocator: Allocator) !*Foo {
return allocator.create(Foo);
}
fn deallocateFoo(allocator: Allocator, foo: *Foo) void {
allocator.destroy(foo);
}
fn getFooData() !u32 {
return 666;
}
fn createFoo(allocator: Allocator, param: i32) !*Foo {
const foo = getFoo: {
var foo = try tryToAllocateFoo(allocator);
errdefer deallocateFoo(allocator, foo); // Only lasts until the end of getFoo
// Calls deallocateFoo on error
foo.data = try getFooData();
break :getFoo foo;
};
// Outside of the scope of the errdefer, so
// deallocateFoo will not be called here
if (param > 1337) return error.InvalidParam;
return foo;
}
test "createFoo" {
try std.testing.expectError(error.InvalidParam, createFoo(std.testing.allocator, 2468));
}
{#code_end#}
<p>
To ensure that {#syntax#}deallocateFoo{#endsyntax#} is properly called
when returning an error, you must add an {#syntax#}errdefer{#endsyntax#} outside of the block:
</p>
{#code_begin|test|test_errdefer_block#}
const std = @import("std");
const Allocator = std.mem.Allocator;
const Foo = struct {
data: u32,
};
fn tryToAllocateFoo(allocator: Allocator) !*Foo {
return allocator.create(Foo);
}
fn deallocateFoo(allocator: Allocator, foo: *Foo) void {
allocator.destroy(foo);
}
fn getFooData() !u32 {
return 666;
}
fn createFoo(allocator: Allocator, param: i32) !*Foo {
const foo = getFoo: {
var foo = try tryToAllocateFoo(allocator);
errdefer deallocateFoo(allocator, foo);
foo.data = try getFooData();
break :getFoo foo;
};
// This lasts for the rest of the function
errdefer deallocateFoo(allocator, foo);
// Error is now properly handled by errdefer
if (param > 1337) return error.InvalidParam;
return foo;
}
test "createFoo" {
try std.testing.expectError(error.InvalidParam, createFoo(std.testing.allocator, 2468));
}
{#code_end#}
<p>
The fact that errdefers only last for the block they are declared in is
especially important when using loops:
</p>
{#code_begin|test_err|test_errdefer_loop_leak|3 errors were logged#}
const std = @import("std");
const Allocator = std.mem.Allocator;
const Foo = struct {
data: *u32
};
fn getData() !u32 {
return 666;
}
fn genFoos(allocator: Allocator, num: usize) ![]Foo {
var foos = try allocator.alloc(Foo, num);
errdefer allocator.free(foos);
for(foos) |*foo, i| {
foo.data = try allocator.create(u32);
// This errdefer does not last between iterations
errdefer allocator.destroy(foo.data);
// The data for the first 3 foos will be leaked
if(i >= 3) return error.TooManyFoos;
foo.data.* = try getData();
}
return foos;
}
test "genFoos" {
try std.testing.expectError(error.TooManyFoos, genFoos(std.testing.allocator, 5));
}
{#code_end#}
<p>
Special care must be taken with code that allocates in a loop
to make sure that no memory is leaked when returning an error:
</p>
{#code_begin|test|test_errdefer_loop#}
const std = @import("std");
const Allocator = std.mem.Allocator;
const Foo = struct {
data: *u32
};
fn getData() !u32 {
return 666;
}
fn genFoos(allocator: Allocator, num: usize) ![]Foo {
var foos = try allocator.alloc(Foo, num);
errdefer allocator.free(foos);
// Used to track how many foos have been initialized
// (including their data being allocated)
var num_allocated: usize = 0;
errdefer for(foos[0..num_allocated]) |foo| {
allocator.destroy(foo.data);
};
for(foos) |*foo, i| {
foo.data = try allocator.create(u32);
num_allocated += 1;
if(i >= 3) return error.TooManyFoos;
foo.data.* = try getData();
}
return foos;
}
test "genFoos" {
try std.testing.expectError(error.TooManyFoos, genFoos(std.testing.allocator, 5));
}
{#code_end#}
{#header_close#}
<p>
A couple of other tidbits about error handling:
</p>
<ul>
<li>These primitives give enough expressiveness that it's completely practical
to have failing to check for an error be a compile error. If you really want
to ignore the error, you can add {#syntax#}catch unreachable{#endsyntax#} and
get the added benefit of crashing in Debug and ReleaseSafe modes if your assumption was wrong.
</li>
<li>
Since Zig understands error types, it can pre-weight branches in favor of
errors not occurring. Just a small optimization benefit that is not available
in other languages.
</li>
</ul>
{#see_also|defer|if|switch#}
<p>An error union is created with the {#syntax#}!{#endsyntax#} binary operator.
You can use compile-time reflection to access the child type of an error union:</p>
{#code_begin|test|test_error_union#}
const expect = @import("std").testing.expect;
test "error union" {
var foo: anyerror!i32 = undefined;
// Coerce from child type of an error union:
foo = 1234;
// Coerce from an error set:
foo = error.SomeError;
// Use compile-time reflection to access the payload type of an error union:
comptime try expect(@typeInfo(@TypeOf(foo)).ErrorUnion.payload == i32);
// Use compile-time reflection to access the error set type of an error union:
comptime try expect(@typeInfo(@TypeOf(foo)).ErrorUnion.error_set == anyerror);
}
{#code_end#}
{#header_open|Merging Error Sets#}
<p>
Use the {#syntax#}||{#endsyntax#} operator to merge two error sets together. The resulting
error set contains the errors of both error sets. Doc comments from the left-hand
side override doc comments from the right-hand side. In this example, the doc
comments for {#syntax#}C.PathNotFound{#endsyntax#} is <code>A doc comment</code>.
</p>
<p>
This is especially useful for functions which return different error sets depending
on {#link|comptime#} branches. For example, the Zig standard library uses
{#syntax#}LinuxFileOpenError || WindowsFileOpenError{#endsyntax#} for the error set of opening
files.
</p>
{#code_begin|test|test_merging_error_sets#}
const A = error{
NotDir,
/// A doc comment
PathNotFound,
};
const B = error{
OutOfMemory,
/// B doc comment
PathNotFound,
};
const C = A || B;
fn foo() C!void {
return error.NotDir;
}
test "merge error sets" {
if (foo()) {
@panic("unexpected");
} else |err| switch (err) {
error.OutOfMemory => @panic("unexpected"),
error.PathNotFound => @panic("unexpected"),
error.NotDir => {},
}
}
{#code_end#}
{#header_close#}
{#header_open|Inferred Error Sets#}
<p>
Because many functions in Zig return a possible error, Zig supports inferring the error set.
To infer the error set for a function, prepend the {#syntax#}!{#endsyntax#} operator to the function’s return type, like {#syntax#}!T{#endsyntax#}:
</p>
{#code_begin|test|test_inferred_error_sets#}
// With an inferred error set
pub fn add_inferred(comptime T: type, a: T, b: T) !T {
const ov = @addWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
// With an explicit error set
pub fn add_explicit(comptime T: type, a: T, b: T) Error!T {
const ov = @addWithOverflow(a, b);
if (ov[1] != 0) return error.Overflow;
return ov[0];
}
const Error = error {
Overflow,
};
const std = @import("std");
test "inferred error set" {
if (add_inferred(u8, 255, 1)) |_| unreachable else |err| switch (err) {
error.Overflow => {}, // ok
}
}
{#code_end#}
<p>
When a function has an inferred error set, that function becomes generic and thus it becomes
trickier to do certain things with it, such as obtain a function pointer, or have an error
set that is consistent across different build targets. Additionally, inferred error sets
are incompatible with recursion.
</p>
<p>
In these situations, it is recommended to use an explicit error set. You can generally start
with an empty error set and let compile errors guide you toward completing the set.
</p>
<p>
These limitations may be overcome in a future version of Zig.
</p>
{#header_close#}
{#header_close#}
{#header_open|Error Return Traces#}
<p>
Error Return Traces show all the points in the code that an error was returned to the calling function. This makes it practical to use {#link|try#} everywhere and then still be able to know what happened if an error ends up bubbling all the way out of your application.
</p>
{#code_begin|exe_err|error_return_trace#}
pub fn main() !void {
try foo(12);
}
fn foo(x: i32) !void {
if (x >= 5) {
try bar();
} else {
try bang2();
}
}
fn bar() !void {
if (baz()) {
try quux();
} else |err| switch (err) {
error.FileNotFound => try hello(),
}
}
fn baz() !void {
try bang1();
}
fn quux() !void {
try bang2();
}
fn hello() !void {
try bang2();
}
fn bang1() !void {
return error.FileNotFound;
}
fn bang2() !void {
return error.PermissionDenied;
}
{#code_end#}
<p>
Look closely at this example. This is no stack trace.
</p>
<p>
You can see that the final error bubbled up was {#syntax#}PermissionDenied{#endsyntax#},
but the original error that started this whole thing was {#syntax#}FileNotFound{#endsyntax#}. In the {#syntax#}bar{#endsyntax#} function, the code handles the original error code,
and then returns another one, from the switch statement. Error Return Traces make this clear, whereas a stack trace would look like this:
</p>
{#code_begin|exe_err|stack_trace#}
pub fn main() void {
foo(12);
}
fn foo(x: i32) void {
if (x >= 5) {
bar();
} else {
bang2();
}
}
fn bar() void {
if (baz()) {
quux();
} else {
hello();
}
}
fn baz() bool {
return bang1();
}
fn quux() void {
bang2();
}
fn hello() void {
bang2();
}
fn bang1() bool {
return false;
}
fn bang2() void {
@panic("PermissionDenied");
}
{#code_end#}
<p>
Here, the stack trace does not explain how the control
flow in {#syntax#}bar{#endsyntax#} got to the {#syntax#}hello(){#endsyntax#} call.
One would have to open a debugger or further instrument the application
in order to find out. The error return trace, on the other hand,
shows exactly how the error bubbled up.
</p>
<p>
This debugging feature makes it easier to iterate quickly on code that
robustly handles all error conditions. This means that Zig developers
will naturally find themselves writing correct, robust code in order
to increase their development pace.
</p>
<p>
Error Return Traces are enabled by default in {#link|Debug#} and {#link|ReleaseSafe#} builds and disabled by default in {#link|ReleaseFast#} and {#link|ReleaseSmall#} builds.
</p>
<p>
There are a few ways to activate this error return tracing feature:
</p>
<ul>
<li>Return an error from main</li>
<li>An error makes its way to {#syntax#}catch unreachable{#endsyntax#} and you have not overridden the default panic handler</li>
<li>Use {#link|errorReturnTrace#} to access the current return trace. You can use {#syntax#}std.debug.dumpStackTrace{#endsyntax#} to print it. This function returns comptime-known {#link|null#} when building without error return tracing support.</li>
</ul>
{#header_open|Implementation Details#}
<p>
To analyze performance cost, there are two cases:
</p>
<ul>
<li>when no errors are returned</li>
<li>when returning errors</li>
</ul>
<p>
For the case when no errors are returned, the cost is a single memory write operation, only in the first non-failable function in the call graph that calls a failable function, i.e. when a function returning {#syntax#}void{#endsyntax#} calls a function returning {#syntax#}error{#endsyntax#}.
This is to initialize this struct in the stack memory:
</p>
{#syntax_block|zig|stack_trace_struct.zig#}
pub const StackTrace = struct {
index: usize,
instruction_addresses: [N]usize,
};
{#end_syntax_block#}
<p>
Here, N is the maximum function call depth as determined by call graph analysis. Recursion is ignored and counts for 2.
</p>
<p>
A pointer to {#syntax#}StackTrace{#endsyntax#} is passed as a secret parameter to every function that can return an error, but it's always the first parameter, so it can likely sit in a register and stay there.
</p>
<p>
That's it for the path when no errors occur. It's practically free in terms of performance.
</p>
<p>
When generating the code for a function that returns an error, just before the {#syntax#}return{#endsyntax#} statement (only for the {#syntax#}return{#endsyntax#} statements that return errors), Zig generates a call to this function:
</p>
{#syntax_block|zig|zig_return_error_fn.zig#}
// marked as "no-inline" in LLVM IR
fn __zig_return_error(stack_trace: *StackTrace) void {
stack_trace.instruction_addresses[stack_trace.index] = @returnAddress();
stack_trace.index = (stack_trace.index + 1) % N;
}
{#end_syntax_block#}
<p>
The cost is 2 math operations plus some memory reads and writes. The memory accessed is constrained and should remain cached for the duration of the error return bubbling.
</p>
<p>
As for code size cost, 1 function call before a return statement is no big deal. Even so,
I have <a href="https://github.com/ziglang/zig/issues/690">a plan</a> to make the call to
{#syntax#}__zig_return_error{#endsyntax#} a tail call, which brings the code size cost down to actually zero. What is a return statement in code without error return tracing can become a jump instruction in code with error return tracing.
</p>
{#header_close#}
{#header_close#}
{#header_close#}
{#header_open|Optionals#}
<p>
One area that Zig provides safety without compromising efficiency or
readability is with the optional type.
</p>
<p>
The question mark symbolizes the optional type. You can convert a type to an optional
type by putting a question mark in front of it, like this:
</p>
{#code_begin|syntax|optional_integer#}
// normal integer
const normal_int: i32 = 1234;
// optional integer
const optional_int: ?i32 = 5678;
{#code_end#}
<p>
Now the variable {#syntax#}optional_int{#endsyntax#} could be an {#syntax#}i32{#endsyntax#}, or {#syntax#}null{#endsyntax#}.
</p>
<p>
Instead of integers, let's talk about pointers. Null references are the source of many runtime
exceptions, and even stand accused of being
<a href="https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/">the worst mistake of computer science</a>.
</p>
<p>Zig does not have them.</p>
<p>
Instead, you can use an optional pointer. This secretly compiles down to a normal pointer,
since we know we can use 0 as the null value for the optional type. But the compiler
can check your work and make sure you don't assign null to something that can't be null.
</p>
<p>
Typically the downside of not having null is that it makes the code more verbose to
write. But, let's compare some equivalent C code and Zig code.
</p>
<p>
Task: call malloc, if the result is null, return null.
</p>
<p>C code</p>
{#syntax_block|c|call_malloc_in_c.c#}
// malloc prototype included for reference
void *malloc(size_t size);
struct Foo *do_a_thing(void) {
char *ptr = malloc(1234);
if (!ptr) return NULL;
// ...
}
{#end_syntax_block#}
<p>Zig code</p>
{#syntax_block|zig|call_malloc_from_zig.zig#}
// malloc prototype included for reference
extern fn malloc(size: size_t) ?*u8;
fn doAThing() ?*Foo {
const ptr = malloc(1234) orelse return null;
_ = ptr; // ...
}
{#end_syntax_block#}
<p>
Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr"
is {#syntax#}*u8{#endsyntax#} <em>not</em> {#syntax#}?*u8{#endsyntax#}. The {#syntax#}orelse{#endsyntax#} keyword
unwrapped the optional type and therefore {#syntax#}ptr{#endsyntax#} is guaranteed to be non-null everywhere
it is used in the function.
</p>
<p>
The other form of checking against NULL you might see looks like this:
</p>
{#syntax_block|c|checking_null_in_c.c#}
void do_a_thing(struct Foo *foo) {
// do some stuff
if (foo) {
do_something_with_foo(foo);
}
// do some stuff
}
{#end_syntax_block#}
<p>
In Zig you can accomplish the same thing:
</p>
{#code_begin|syntax|checking_null_in_zig#}
const Foo = struct{};
fn doSomethingWithFoo(foo: *Foo) void { _ = foo; }
fn doAThing(optional_foo: ?*Foo) void {
// do some stuff
if (optional_foo) |foo| {
doSomethingWithFoo(foo);
}
// do some stuff
}
{#code_end#}
<p>
Once again, the notable thing here is that inside the if block,
{#syntax#}foo{#endsyntax#} is no longer an optional pointer, it is a pointer, which
cannot be null.
</p>
<p>
One benefit to this is that functions which take pointers as arguments can
be annotated with the "nonnull" attribute - <code>__attribute__((nonnull))</code> in
<a href="https://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html">GCC</a>.
The optimizer can sometimes make better decisions knowing that pointer arguments
cannot be null.
</p>
{#header_open|Optional Type#}
<p>An optional is created by putting {#syntax#}?{#endsyntax#} in front of a type. You can use compile-time
reflection to access the child type of an optional:</p>
{#code_begin|test|test_optional_type#}
const expect = @import("std").testing.expect;
test "optional type" {
// Declare an optional and coerce from null:
var foo: ?i32 = null;
// Coerce from child type of an optional
foo = 1234;
// Use compile-time reflection to access the child type of the optional:
comptime try expect(@typeInfo(@TypeOf(foo)).Optional.child == i32);
}
{#code_end#}
{#header_close#}
{#header_open|null#}
<p>
Just like {#link|undefined#}, {#syntax#}null{#endsyntax#} has its own type, and the only way to use it is to
cast it to a different type:
</p>
{#code_begin|syntax|null#}
const optional_value: ?i32 = null;
{#code_end#}
{#header_close#}
{#header_open|Optional Pointers#}
<p>An optional pointer is guaranteed to be the same size as a pointer. The {#syntax#}null{#endsyntax#} of
the optional is guaranteed to be address 0.</p>
{#code_begin|test|test_optional_pointer#}
const expect = @import("std").testing.expect;
test "optional pointers" {
// Pointers cannot be null. If you want a null pointer, use the optional
// prefix `?` to make the pointer type optional.
var ptr: ?*i32 = null;
var x: i32 = 1;
ptr = &x;
try expect(ptr.?.* == 1);
// Optional pointers are the same size as normal pointers, because pointer
// value 0 is used as the null value.
try expect(@sizeOf(?*i32) == @sizeOf(*i32));
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Casting#}
<p>
A <strong>type cast</strong> converts a value of one type to another.
Zig has {#link|Type Coercion#} for conversions that are known to be completely safe and unambiguous,
and {#link|Explicit Casts#} for conversions that one would not want to happen on accident.
There is also a third kind of type conversion called {#link|Peer Type Resolution#} for
the case when a result type must be decided given multiple operand types.
</p>
{#header_open|Type Coercion#}
<p>
Type coercion occurs when one type is expected, but different type is provided:
</p>
{#code_begin|test|test_type_coercion#}
test "type coercion - variable declaration" {
var a: u8 = 1;
var b: u16 = a;
_ = b;
}
test "type coercion - function call" {
var a: u8 = 1;
foo(a);
}
fn foo(b: u16) void {
_ = b;
}
test "type coercion - @as builtin" {
var a: u8 = 1;
var b = @as(u16, a);
_ = b;
}
{#code_end#}
<p>
Type coercions are only allowed when it is completely unambiguous how to get from one type to another,
and the transformation is guaranteed to be safe. There is one exception, which is {#link|C Pointers#}.
</p>
{#header_open|Type Coercion: Stricter Qualification#}
<p>
Values which have the same representation at runtime can be cast to increase the strictness
of the qualifiers, no matter how nested the qualifiers are:
</p>
<ul>
<li>{#syntax#}const{#endsyntax#} - non-const to const is allowed</li>
<li>{#syntax#}volatile{#endsyntax#} - non-volatile to volatile is allowed</li>
<li>{#syntax#}align{#endsyntax#} - bigger to smaller alignment is allowed </li>
<li>{#link|error sets|Error Set Type#} to supersets is allowed</li>
</ul>
<p>
These casts are no-ops at runtime since the value representation does not change.
</p>
{#code_begin|test|test_no_op_casts#}
test "type coercion - const qualification" {
var a: i32 = 1;
var b: *i32 = &a;
foo(b);
}
fn foo(_: *const i32) void {}
{#code_end#}
<p>
In addition, pointers coerce to const optional pointers:
</p>
{#code_begin|test|test_pointer_coerce_const_optional#}
const std = @import("std");
const expect = std.testing.expect;
const mem = std.mem;
test "cast *[1][*]const u8 to [*]const ?[*]const u8" {
const window_name = [1][*]const u8{"window name"};
const x: [*]const ?[*]const u8 = &window_name;
try expect(mem.eql(u8, std.mem.sliceTo(@ptrCast([*:0]const u8, x[0].?), 0), "window name"));
}
{#code_end#}
{#header_close#}
{#header_open|Type Coercion: Integer and Float Widening#}
<p>
{#link|Integers#} coerce to integer types which can represent every value of the old type, and likewise
{#link|Floats#} coerce to float types which can represent every value of the old type.
</p>
{#code_begin|test|test_integer_widening#}
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
const mem = std.mem;
test "integer widening" {
var a: u8 = 250;
var b: u16 = a;
var c: u32 = b;
var d: u64 = c;
var e: u64 = d;
var f: u128 = e;
try expect(f == a);
}
test "implicit unsigned integer to signed integer" {
var a: u8 = 250;
var b: i16 = a;
try expect(b == 250);
}
test "float widening" {
var a: f16 = 12.34;
var b: f32 = a;
var c: f64 = b;
var d: f128 = c;
try expect(d == a);
}
{#code_end#}
{#header_close#}
{#header_open|Type Coercion: Float to Int#}
<p>
A compiler error is appropriate because this ambiguous expression leaves the compiler
two choices about the coercion.
</p>
<ul>
<li>Cast {#syntax#}54.0{#endsyntax#} to {#syntax#}comptime_int{#endsyntax#} resulting in {#syntax#}@as(comptime_int, 10){#endsyntax#}, which is casted to {#syntax#}@as(f32, 10){#endsyntax#}</li>
<li>Cast {#syntax#}5{#endsyntax#} to {#syntax#}comptime_float{#endsyntax#} resulting in {#syntax#}@as(comptime_float, 10.8){#endsyntax#}, which is casted to {#syntax#}@as(f32, 10.8){#endsyntax#}</li>
</ul>
{#code_begin|test_err|test_ambiguous_coercion#}
// Compile time coercion of float to int
test "implicit cast to comptime_int" {
var f: f32 = 54.0 / 5;
_ = f;
}
{#code_end#}
{#header_close#}
{#header_open|Type Coercion: Slices, Arrays and Pointers#}
{#code_begin|test|test_coerce_slices_arrays_and_pointers#}
const std = @import("std");
const expect = std.testing.expect;
// You can assign constant pointers to arrays to a slice with
// const modifier on the element type. Useful in particular for
// String literals.
test "*const [N]T to []const T" {
var x1: []const u8 = "hello";
var x2: []const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
try expect(std.mem.eql(u8, x1, x2));
var y: []const f32 = &[2]f32{ 1.2, 3.4 };
try expect(y[0] == 1.2);
}
// Likewise, it works when the destination type is an error union.
test "*const [N]T to E![]const T" {
var x1: anyerror![]const u8 = "hello";
var x2: anyerror![]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
try expect(std.mem.eql(u8, try x1, try x2));
var y: anyerror![]const f32 = &[2]f32{ 1.2, 3.4 };
try expect((try y)[0] == 1.2);
}
// Likewise, it works when the destination type is an optional.
test "*const [N]T to ?[]const T" {
var x1: ?[]const u8 = "hello";
var x2: ?[]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
try expect(std.mem.eql(u8, x1.?, x2.?));
var y: ?[]const f32 = &[2]f32{ 1.2, 3.4 };
try expect(y.?[0] == 1.2);
}
// In this cast, the array length becomes the slice length.
test "*[N]T to []T" {
var buf: [5]u8 = "hello".*;
const x: []u8 = &buf;
try expect(std.mem.eql(u8, x, "hello"));
const buf2 = [2]f32{ 1.2, 3.4 };
const x2: []const f32 = &buf2;
try expect(std.mem.eql(f32, x2, &[2]f32{ 1.2, 3.4 }));
}
// Single-item pointers to arrays can be coerced to many-item pointers.
test "*[N]T to [*]T" {
var buf: [5]u8 = "hello".*;
const x: [*]u8 = &buf;
try expect(x[4] == 'o');
// x[5] would be an uncaught out of bounds pointer dereference!
}
// Likewise, it works when the destination type is an optional.
test "*[N]T to ?[*]T" {
var buf: [5]u8 = "hello".*;
const x: ?[*]u8 = &buf;
try expect(x.?[4] == 'o');
}
// Single-item pointers can be cast to len-1 single-item arrays.
test "*T to *[1]T" {
var x: i32 = 1234;
const y: *[1]i32 = &x;
const z: [*]i32 = y;
try expect(z[0] == 1234);
}
{#code_end#}
{#see_also|C Pointers#}
{#header_close#}
{#header_open|Type Coercion: Optionals#}
<p>
The payload type of {#link|Optionals#}, as well as {#link|null#}, coerce to the optional type.
</p>
{#code_begin|test|test_coerce_optionals#}
const std = @import("std");
const expect = std.testing.expect;
test "coerce to optionals" {
const x: ?i32 = 1234;
const y: ?i32 = null;
try expect(x.? == 1234);
try expect(y == null);
}
{#code_end#}
<p>It works nested inside the {#link|Error Union Type#}, too:</p>
{#code_begin|test|test_coerce_optional_wrapped_error_union#}
const std = @import("std");
const expect = std.testing.expect;
test "coerce to optionals wrapped in error union" {
const x: anyerror!?i32 = 1234;
const y: anyerror!?i32 = null;
try expect((try x).? == 1234);
try expect((try y) == null);
}
{#code_end#}
{#header_close#}
{#header_open|Type Coercion: Error Unions#}
<p>The payload type of an {#link|Error Union Type#} as well as the {#link|Error Set Type#}
coerce to the error union type:
</p>
{#code_begin|test|test_coerce_to_error_union#}
const std = @import("std");
const expect = std.testing.expect;
test "coercion to error unions" {
const x: anyerror!i32 = 1234;
const y: anyerror!i32 = error.Failure;
try expect((try x) == 1234);
try std.testing.expectError(error.Failure, y);
}
{#code_end#}
{#header_close#}
{#header_open|Type Coercion: Compile-Time Known Numbers#}
<p>When a number is {#link|comptime#}-known to be representable in the destination type,
it may be coerced:
</p>
{#code_begin|test|test_coerce_large_to_small#}
const std = @import("std");
const expect = std.testing.expect;
test "coercing large integer type to smaller one when value is comptime-known to fit" {
const x: u64 = 255;
const y: u8 = x;
try expect(y == 255);
}
{#code_end#}
{#header_close#}
{#header_open|Type Coercion: Unions and Enums#}
<p>Tagged unions can be coerced to enums, and enums can be coerced to tagged unions
when they are {#link|comptime#}-known to be a field of the union that has only one possible value, such as
{#link|void#}:
</p>
{#code_begin|test|test_coerce_unions_enums#}
const std = @import("std");
const expect = std.testing.expect;
const E = enum {
one,
two,
three,
};
const U = union(E) {
one: i32,
two: f32,
three,
};
const U2 = union(enum) {
a: void,
b: f32,
fn tag(self: U2) usize {
switch (self) {
.a => return 1,
.b => return 2,
}
}
};
test "coercion between unions and enums" {
var u = U{ .two = 12.34 };
var e: E = u; // coerce union to enum
try expect(e == E.two);
const three = E.three;
var u_2: U = three; // coerce enum to union
try expect(u_2 == E.three);
var u_3: U = .three; // coerce enum literal to union
try expect(u_3 == E.three);
var u_4: U2 = .a; // coerce enum literal to union with inferred enum tag type.
try expect(u_4.tag() == 1);
// The following example is invalid.
// error: coercion from enum '@TypeOf(.enum_literal)' to union 'test_coerce_unions_enum.U2' must initialize 'f32' field 'b'
//var u_5: U2 = .b;
//try expect(u_5.tag() == 2);
}
{#code_end#}
{#see_also|union|enum#}
{#header_close#}
{#header_open|Type Coercion: undefined#}
<p>{#link|undefined#} can be coerced to any type.</p>
{#header_close#}
{#header_open|Type Coercion: Tuples to Arrays#}
<p>{#link|Tuples#} can be coerced to arrays, if all of the fields have the same type.</p>
{#code_begin|test|test_coerce_tuples_arrays#}
const std = @import("std");
const expect = std.testing.expect;
const Tuple = struct{ u8, u8 };
test "coercion from homogenous tuple to array" {
const tuple: Tuple = .{5, 6};
const array: [2]u8 = tuple;
_ = array;
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Explicit Casts#}
<p>
Explicit casts are performed via {#link|Builtin Functions#}.
Some explicit casts are safe; some are not.
Some explicit casts perform language-level assertions; some do not.
Some explicit casts are no-ops at runtime; some are not.
</p>
<ul>
<li>{#link|@bitCast#} - change type but maintain bit representation</li>
<li>{#link|@alignCast#} - make a pointer have more alignment</li>
<li>{#link|@boolToInt#} - convert true to 1 and false to 0</li>
<li>{#link|@enumToInt#} - obtain the integer tag value of an enum or tagged union</li>
<li>{#link|@errSetCast#} - convert to a smaller error set</li>
<li>{#link|@errorToInt#} - obtain the integer value of an error code</li>
<li>{#link|@floatCast#} - convert a larger float to a smaller float</li>
<li>{#link|@floatToInt#} - obtain the integer part of a float value</li>
<li>{#link|@intCast#} - convert between integer types</li>
<li>{#link|@intToEnum#} - obtain an enum value based on its integer tag value</li>
<li>{#link|@intToError#} - obtain an error code based on its integer value</li>
<li>{#link|@intToFloat#} - convert an integer to a float value</li>
<li>{#link|@intToPtr#} - convert an address to a pointer</li>
<li>{#link|@ptrCast#} - convert between pointer types</li>
<li>{#link|@ptrToInt#} - obtain the address of a pointer</li>
<li>{#link|@truncate#} - convert between integer types, chopping off bits</li>
</ul>
{#header_close#}
{#header_open|Peer Type Resolution#}
<p>Peer Type Resolution occurs in these places:</p>
<ul>
<li>{#link|switch#} expressions</li>
<li>{#link|if#} expressions</li>
<li>{#link|while#} expressions</li>
<li>{#link|for#} expressions</li>
<li>Multiple break statements in a block</li>
<li>Some {#link|binary operations|Table of Operators#}</li>
</ul>
<p>
This kind of type resolution chooses a type that all peer types can coerce into. Here are
some examples:
</p>
{#code_begin|test|test_peer_type_resolution#}
const std = @import("std");
const expect = std.testing.expect;
const mem = std.mem;
test "peer resolve int widening" {
var a: i8 = 12;
var b: i16 = 34;
var c = a + b;
try expect(c == 46);
try expect(@TypeOf(c) == i16);
}
test "peer resolve arrays of different size to const slice" {
try expect(mem.eql(u8, boolToStr(true), "true"));
try expect(mem.eql(u8, boolToStr(false), "false"));
comptime try expect(mem.eql(u8, boolToStr(true), "true"));
comptime try expect(mem.eql(u8, boolToStr(false), "false"));
}
fn boolToStr(b: bool) []const u8 {
return if (b) "true" else "false";
}
test "peer resolve array and const slice" {
try testPeerResolveArrayConstSlice(true);
comptime try testPeerResolveArrayConstSlice(true);
}
fn testPeerResolveArrayConstSlice(b: bool) !void {
const value1 = if (b) "aoeu" else @as([]const u8, "zz");
const value2 = if (b) @as([]const u8, "zz") else "aoeu";
try expect(mem.eql(u8, value1, "aoeu"));
try expect(mem.eql(u8, value2, "zz"));
}
test "peer type resolution: ?T and T" {
try expect(peerTypeTAndOptionalT(true, false).? == 0);
try expect(peerTypeTAndOptionalT(false, false).? == 3);
comptime {
try expect(peerTypeTAndOptionalT(true, false).? == 0);
try expect(peerTypeTAndOptionalT(false, false).? == 3);
}
}
fn peerTypeTAndOptionalT(c: bool, b: bool) ?usize {
if (c) {
return if (b) null else @as(usize, 0);
}
return @as(usize, 3);
}
test "peer type resolution: *[0]u8 and []const u8" {
try expect(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
try expect(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
comptime {
try expect(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
try expect(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
}
}
fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 {
if (a) {
return &[_]u8{};
}
return slice[0..1];
}
test "peer type resolution: *[0]u8, []const u8, and anyerror![]u8" {
{
var data = "hi".*;
const slice = data[0..];
try expect((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
try expect((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
comptime {
var data = "hi".*;
const slice = data[0..];
try expect((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
try expect((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
}
fn peerTypeEmptyArrayAndSliceAndError(a: bool, slice: []u8) anyerror![]u8 {
if (a) {
return &[_]u8{};
}
return slice[0..1];
}
test "peer type resolution: *const T and ?*T" {
const a = @intToPtr(*const usize, 0x123456780);
const b = @intToPtr(?*usize, 0x123456780);
try expect(a == b);
try expect(b == a);
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Zero Bit Types#}
<p>For some types, {#link|@sizeOf#} is 0:</p>
<ul>
<li>{#link|void#}</li>
<li>The {#link|Integers#} {#syntax#}u0{#endsyntax#} and {#syntax#}i0{#endsyntax#}.</li>
<li>{#link|Arrays#} and {#link|Vectors#} with len 0, or with an element type that is a zero bit type.</li>
<li>An {#link|enum#} with only 1 tag.</li>
<li>A {#link|struct#} with all fields being zero bit types.</li>
<li>A {#link|union#} with only 1 field which is a zero bit type.</li>
</ul>
<p>
These types can only ever have one possible value, and thus
require 0 bits to represent. Code that makes use of these types is
not included in the final generated code:
</p>
{#code_begin|syntax|zero_bit_types#}
export fn entry() void {
var x: void = {};
var y: void = {};
x = y;
}
{#code_end#}
<p>When this turns into machine code, there is no code generated in the
body of {#syntax#}entry{#endsyntax#}, even in {#link|Debug#} mode. For example, on x86_64:</p>
<pre><code>0000000000000010 <entry>:
10: 55 push %rbp
11: 48 89 e5 mov %rsp,%rbp
14: 5d pop %rbp
15: c3 retq </code></pre>
<p>These assembly instructions do not have any code associated with the void values -
they only perform the function call prologue and epilogue.</p>
{#header_open|void#}
<p>
{#syntax#}void{#endsyntax#} can be useful for instantiating generic types. For example, given a
{#syntax#}Map(Key, Value){#endsyntax#}, one can pass {#syntax#}void{#endsyntax#} for the {#syntax#}Value{#endsyntax#}
type to make it into a {#syntax#}Set{#endsyntax#}:
</p>
{#code_begin|test|test_void_in_hashmap#}
const std = @import("std");
const expect = std.testing.expect;
test "turn HashMap into a set with void" {
var map = std.AutoHashMap(i32, void).init(std.testing.allocator);
defer map.deinit();
try map.put(1, {});
try map.put(2, {});
try expect(map.contains(2));
try expect(!map.contains(3));
_ = map.remove(2);
try expect(!map.contains(2));
}
{#code_end#}
<p>Note that this is different from using a dummy value for the hash map value.
By using {#syntax#}void{#endsyntax#} as the type of the value, the hash map entry type has no value field, and
thus the hash map takes up less space. Further, all the code that deals with storing and loading the
value is deleted, as seen above.
</p>
<p>
{#syntax#}void{#endsyntax#} is distinct from {#syntax#}anyopaque{#endsyntax#}.
{#syntax#}void{#endsyntax#} has a known size of 0 bytes, and {#syntax#}anyopaque{#endsyntax#} has an unknown, but non-zero, size.
</p>
<p>
Expressions of type {#syntax#}void{#endsyntax#} are the only ones whose value can be ignored. For example:
</p>
{#code_begin|test_err|test_expression_ignored|ignored#}
test "ignoring expression value" {
foo();
}
fn foo() i32 {
return 1234;
}
{#code_end#}
<p>However, if the expression has type {#syntax#}void{#endsyntax#}, there will be no error. Function return values can also be explicitly ignored by assigning them to {#syntax#}_{#endsyntax#}. </p>
{#code_begin|test|test_void_ignored#}
test "void is ignored" {
returnsVoid();
}
test "explicitly ignoring expression value" {
_ = foo();
}
fn returnsVoid() void {}
fn foo() i32 {
return 1234;
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Result Location Semantics#}
<p>
<a href="https://github.com/ziglang/zig/issues/2809">TODO add documentation for this</a>
</p>
{#header_close#}
{#header_open|usingnamespace#}
<p>
{#syntax#}usingnamespace{#endsyntax#} is a declaration that mixes all the public
declarations of the operand, which must be a {#link|struct#}, {#link|union#}, {#link|enum#},
or {#link|opaque#}, into the namespace:
</p>
{#code_begin|test|test_usingnamespace#}
test "using std namespace" {
const S = struct {
usingnamespace @import("std");
};
try S.testing.expect(true);
}
{#code_end#}
<p>
{#syntax#}usingnamespace{#endsyntax#} has an important use case when organizing the public
API of a file or package. For example, one might have <code class="file">c.zig</code> with all of the
{#link|C imports|Import from C Header File#}:
</p>
{#syntax_block|zig|c.zig#}
pub usingnamespace @cImport({
@cInclude("epoxy/gl.h");
@cInclude("GLFW/glfw3.h");
@cDefine("STBI_ONLY_PNG", "");
@cDefine("STBI_NO_STDIO", "");
@cInclude("stb_image.h");
});
{#end_syntax_block#}
<p>
The above example demonstrates using {#syntax#}pub{#endsyntax#} to qualify the
{#syntax#}usingnamespace{#endsyntax#} additionally makes the imported declarations
{#syntax#}pub{#endsyntax#}. This can be used to forward declarations, giving precise control
over what declarations a given file exposes.
</p>
{#header_close#}
{#header_open|comptime#}
<p>
Zig places importance on the concept of whether an expression is known at compile-time.
There are a few different places this concept is used, and these building blocks are used
to keep the language small, readable, and powerful.
</p>
{#header_open|Introducing the Compile-Time Concept#}
{#header_open|Compile-Time Parameters#}
<p>
Compile-time parameters is how Zig implements generics. It is compile-time duck typing.
</p>
{#code_begin|syntax|compile-time_duck_typing#}
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
fn gimmeTheBiggerFloat(a: f32, b: f32) f32 {
return max(f32, a, b);
}
fn gimmeTheBiggerInteger(a: u64, b: u64) u64 {
return max(u64, a, b);
}
{#code_end#}
<p>
In Zig, types are first-class citizens. They can be assigned to variables, passed as parameters to functions,
and returned from functions. However, they can only be used in expressions which are known at <em>compile-time</em>,
which is why the parameter {#syntax#}T{#endsyntax#} in the above snippet must be marked with {#syntax#}comptime{#endsyntax#}.
</p>
<p>
A {#syntax#}comptime{#endsyntax#} parameter means that:
</p>
<ul>
<li>At the callsite, the value must be known at compile-time, or it is a compile error.</li>
<li>In the function definition, the value is known at compile-time.</li>
</ul>
<p>
For example, if we were to introduce another function to the above snippet:
</p>
{#code_begin|test_err|test_unresolved_comptime_value|unable to resolve comptime value#}
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
test "try to pass a runtime type" {
foo(false);
}
fn foo(condition: bool) void {
const result = max(
if (condition) f32 else u64,
1234,
5678);
_ = result;
}
{#code_end#}
<p>
This is an error because the programmer attempted to pass a value only known at run-time
to a function which expects a value known at compile-time.
</p>
<p>
Another way to get an error is if we pass a type that violates the type checker when the
function is analyzed. This is what it means to have <em>compile-time duck typing</em>.
</p>
<p>
For example:
</p>
{#code_begin|test_err|test_comptime_mismatched_type|operator > not allowed for type 'bool'#}
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
test "try to compare bools" {
_ = max(bool, true, false);
}
{#code_end#}
<p>
On the flip side, inside the function definition with the {#syntax#}comptime{#endsyntax#} parameter, the
value is known at compile-time. This means that we actually could make this work for the bool type
if we wanted to:
</p>
{#code_begin|test|test_comptime_max_with_bool#}
fn max(comptime T: type, a: T, b: T) T {
if (T == bool) {
return a or b;
} else if (a > b) {
return a;
} else {
return b;
}
}
test "try to compare bools" {
try @import("std").testing.expect(max(bool, false, true) == true);
}
{#code_end#}
<p>
This works because Zig implicitly inlines {#syntax#}if{#endsyntax#} expressions when the condition
is known at compile-time, and the compiler guarantees that it will skip analysis of
the branch not taken.
</p>
<p>
This means that the actual function generated for {#syntax#}max{#endsyntax#} in this situation looks like
this:
</p>
{#code_begin|syntax|compiler_generated_function#}
fn max(a: bool, b: bool) bool {
return a or b;
}
{#code_end#}
<p>
All the code that dealt with compile-time known values is eliminated and we are left with only
the necessary run-time code to accomplish the task.
</p>
<p>
This works the same way for {#syntax#}switch{#endsyntax#} expressions - they are implicitly inlined
when the target expression is compile-time known.
</p>
{#header_close#}
{#header_open|Compile-Time Variables#}
<p>
In Zig, the programmer can label variables as {#syntax#}comptime{#endsyntax#}. This guarantees to the compiler
that every load and store of the variable is performed at compile-time. Any violation of this results in a
compile error.
</p>
<p>
This combined with the fact that we can {#syntax#}inline{#endsyntax#} loops allows us to write
a function which is partially evaluated at compile-time and partially at run-time.
</p>
<p>
For example:
</p>
{#code_begin|test|test_comptime_evaluation#}
const expect = @import("std").testing.expect;
const CmdFn = struct {
name: []const u8,
func: fn(i32) i32,
};
const cmd_fns = [_]CmdFn{
CmdFn {.name = "one", .func = one},
CmdFn {.name = "two", .func = two},
CmdFn {.name = "three", .func = three},
};
fn one(value: i32) i32 { return value + 1; }
fn two(value: i32) i32 { return value + 2; }
fn three(value: i32) i32 { return value + 3; }
fn performFn(comptime prefix_char: u8, start_value: i32) i32 {
var result: i32 = start_value;
comptime var i = 0;
inline while (i < cmd_fns.len) : (i += 1) {
if (cmd_fns[i].name[0] == prefix_char) {
result = cmd_fns[i].func(result);
}
}
return result;
}
test "perform fn" {
try expect(performFn('t', 1) == 6);
try expect(performFn('o', 0) == 1);
try expect(performFn('w', 99) == 99);
}
{#code_end#}
<p>
This example is a bit contrived, because the compile-time evaluation component is unnecessary;
this code would work fine if it was all done at run-time. But it does end up generating
different code. In this example, the function {#syntax#}performFn{#endsyntax#} is generated three different times,
for the different values of {#syntax#}prefix_char{#endsyntax#} provided:
</p>
{#syntax_block|zig|performFn_1#}
// From the line:
// expect(performFn('t', 1) == 6);
fn performFn(start_value: i32) i32 {
var result: i32 = start_value;
result = two(result);
result = three(result);
return result;
}
{#end_syntax_block#}
{#syntax_block|zig|performFn_2#}
// From the line:
// expect(performFn('o', 0) == 1);
fn performFn(start_value: i32) i32 {
var result: i32 = start_value;
result = one(result);
return result;
}
{#end_syntax_block#}
{#syntax_block|zig|performFn_3#}
// From the line:
// expect(performFn('w', 99) == 99);
fn performFn(start_value: i32) i32 {
var result: i32 = start_value;
return result;
}
{#end_syntax_block#}
<p>
Note that this happens even in a debug build; in a release build these generated functions still
pass through rigorous LLVM optimizations. The important thing to note, however, is not that this
is a way to write more optimized code, but that it is a way to make sure that what <em>should</em> happen
at compile-time, <em>does</em> happen at compile-time. This catches more errors and as demonstrated
later in this article, allows expressiveness that in other languages requires using macros,
generated code, or a preprocessor to accomplish.
</p>
{#header_close#}
{#header_open|Compile-Time Expressions#}
<p>
In Zig, it matters whether a given expression is known at compile-time or run-time. A programmer can
use a {#syntax#}comptime{#endsyntax#} expression to guarantee that the expression will be evaluated at compile-time.
If this cannot be accomplished, the compiler will emit an error. For example:
</p>
{#code_begin|test_err|test_comptime_call_extern_function|comptime call of extern function#}
extern fn exit() noreturn;
test "foo" {
comptime {
exit();
}
}
{#code_end#}
<p>
It doesn't make sense that a program could call {#syntax#}exit(){#endsyntax#} (or any other external function)
at compile-time, so this is a compile error. However, a {#syntax#}comptime{#endsyntax#} expression does much
more than sometimes cause a compile error.
</p>
<p>
Within a {#syntax#}comptime{#endsyntax#} expression:
</p>
<ul>
<li>All variables are {#syntax#}comptime{#endsyntax#} variables.</li>
<li>All {#syntax#}if{#endsyntax#}, {#syntax#}while{#endsyntax#}, {#syntax#}for{#endsyntax#}, and {#syntax#}switch{#endsyntax#}
expressions are evaluated at compile-time, or emit a compile error if this is not possible.</li>
<li>All function calls cause the compiler to interpret the function at compile-time, emitting a
compile error if the function tries to do something that has global run-time side effects.</li>
</ul>
<p>
This means that a programmer can create a function which is called both at compile-time and run-time, with
no modification to the function required.
</p>
<p>
Let's look at an example:
</p>
{#code_begin|test|test_fibonacci_recursion#}
const expect = @import("std").testing.expect;
fn fibonacci(index: u32) u32 {
if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
// test fibonacci at run-time
try expect(fibonacci(7) == 13);
// test fibonacci at compile-time
comptime {
try expect(fibonacci(7) == 13);
}
}
{#code_end#}
<p>
Imagine if we had forgotten the base case of the recursive function and tried to run the tests:
</p>
{#code_begin|test_err|test_fibonacci_comptime_overflow|overflow of integer type#}
const expect = @import("std").testing.expect;
fn fibonacci(index: u32) u32 {
//if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
comptime {
try expect(fibonacci(7) == 13);
}
}
{#code_end#}
<p>
The compiler produces an error which is a stack trace from trying to evaluate the
function at compile-time.
</p>
<p>
Luckily, we used an unsigned integer, and so when we tried to subtract 1 from 0, it triggered
undefined behavior, which is always a compile error if the compiler knows it happened.
But what would have happened if we used a signed integer?
</p>
{#code_begin|syntax|fibonacci_comptime_infinite_recursion#}
const assert = @import("std").debug.assert;
fn fibonacci(index: i32) i32 {
//if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
comptime {
try assert(fibonacci(7) == 13);
}
}
{#code_end#}
<p>
The compiler is supposed to notice that evaluating this function at
compile-time took more than 1000 branches, and thus emits an error and
gives up. If the programmer wants to increase the budget for compile-time
computation, they can use a built-in function called
{#link|@setEvalBranchQuota#} to change the default number 1000 to
something else.
</p>
<p>
However, there is a <a href="https://github.com/ziglang/zig/issues/13724">design
flaw in the compiler</a> causing it to stack overflow instead of having the proper
behavior here. I'm terribly sorry about that. I hope to get this resolved
before the next release.
</p>
<p>
What if we fix the base case, but put the wrong value in the
{#syntax#}expect{#endsyntax#} line?
</p>
{#code_begin|test_err|test_fibonacci_comptime_unreachable|reached unreachable#}
const assert = @import("std").debug.assert;
fn fibonacci(index: i32) i32 {
if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
comptime {
try assert(fibonacci(7) == 99999);
}
}
{#code_end#}
<p>
At {#link|container|Containers#} level (outside of any function), all expressions are implicitly
{#syntax#}comptime{#endsyntax#} expressions. This means that we can use functions to
initialize complex static data. For example:
</p>
{#code_begin|test|test_container-level_comptime_expressions#}
const first_25_primes = firstNPrimes(25);
const sum_of_first_25_primes = sum(&first_25_primes);
fn firstNPrimes(comptime n: usize) [n]i32 {
var prime_list: [n]i32 = undefined;
var next_index: usize = 0;
var test_number: i32 = 2;
while (next_index < prime_list.len) : (test_number += 1) {
var test_prime_index: usize = 0;
var is_prime = true;
while (test_prime_index < next_index) : (test_prime_index += 1) {
if (test_number % prime_list[test_prime_index] == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
prime_list[next_index] = test_number;
next_index += 1;
}
}
return prime_list;
}
fn sum(numbers: []const i32) i32 {
var result: i32 = 0;
for (numbers) |x| {
result += x;
}
return result;
}
test "variable values" {
try @import("std").testing.expect(sum_of_first_25_primes == 1060);
}
{#code_end#}
<p>
When we compile this program, Zig generates the constants
with the answer pre-computed. Here are the lines from the generated LLVM IR:
</p>
<pre><code class="llvm">@0 = internal unnamed_addr constant [25 x i32] [i32 2, i32 3, i32 5, i32 7, i32 11, i32 13, i32 17, i32 19, i32 23, i32 29, i32 31, i32 37, i32 41, i32 43, i32 47, i32 53, i32 59, i32 61, i32 67, i32 71, i32 73, i32 79, i32 83, i32 89, i32 97]
@1 = internal unnamed_addr constant i32 1060</code></pre>
<p>
Note that we did not have to do anything special with the syntax of these functions. For example,
we could call the {#syntax#}sum{#endsyntax#} function as is with a slice of numbers whose length and values were
only known at run-time.
</p>
{#header_close#}
{#header_close#}
{#header_open|Generic Data Structures#}
<p>
Zig uses these capabilities to implement generic data structures without introducing any
special-case syntax. If you followed along so far, you may already know how to create a
generic data structure.
</p>
<p>
Here is an example of a generic {#syntax#}List{#endsyntax#} data structure.
</p>
{#code_begin|syntax|generic_data_structure#}
fn List(comptime T: type) type {
return struct {
items: []T,
len: usize,
};
}
// The generic List data structure can be instantiated by passing in a type:
var buffer: [10]i32 = undefined;
var list = List(i32){
.items = &buffer,
.len = 0,
};
{#code_end#}
<p>
That's it. It's a function that returns an anonymous {#syntax#}struct{#endsyntax#}.
To keep the language small and uniform, all aggregate types in Zig are anonymous.
For the purposes of error messages and debugging, Zig infers the name
{#syntax#}"List(i32)"{#endsyntax#} from the function name and parameters invoked when creating
the anonymous struct.
</p>
<p>
To explicitly give a type a name, we assign it to a constant.
</p>
{#code_begin|syntax|anonymous_struct_name#}
const Node = struct {
next: ?*Node,
name: []const u8,
};
var node_a = Node{
.next = null,
.name = &"Node A",
};
var node_b = Node{
.next = &node_a,
.name = &"Node B",
};
{#code_end#}
<p>
In this example, the {#syntax#}Node{#endsyntax#} struct refers to itself.
This works because all top level declarations are order-independent.
As long as the compiler can determine the size of the struct, it is free to refer to itself.
In this case, {#syntax#}Node{#endsyntax#} refers to itself as a pointer, which has a
well-defined size at compile time, so it works fine.
</p>
{#header_close#}
{#header_open|Case Study: print in Zig#}
<p>
Putting all of this together, let's see how {#syntax#}print{#endsyntax#} works in Zig.
</p>
{#code_begin|exe|print#}
const print = @import("std").debug.print;
const a_number: i32 = 1234;
const a_string = "foobar";
pub fn main() void {
print("here is a string: '{s}' here is a number: {}\n", .{a_string, a_number});
}
{#code_end#}
<p>
Let's crack open the implementation of this and see how it works:
</p>
{#code_begin|syntax|poc_print_fn#}
const Writer = struct {
/// Calls print and then flushes the buffer.
pub fn print(self: *Writer, comptime format: []const u8, args: anytype) anyerror!void {
const State = enum {
start,
open_brace,
close_brace,
};
comptime var start_index: usize = 0;
comptime var state = State.start;
comptime var next_arg: usize = 0;
inline for (format) |c, i| {
switch (state) {
State.start => switch (c) {
'{' => {
if (start_index < i) try self.write(format[start_index..i]);
state = State.open_brace;
},
'}' => {
if (start_index < i) try self.write(format[start_index..i]);
state = State.close_brace;
},
else => {},
},
State.open_brace => switch (c) {
'{' => {
state = State.start;
start_index = i;
},
'}' => {
try self.printValue(args[next_arg]);
next_arg += 1;
state = State.start;
start_index = i + 1;
},
's' => {
continue;
},
else => @compileError("Unknown format character: " ++ [1]u8{c}),
},
State.close_brace => switch (c) {
'}' => {
state = State.start;
start_index = i;
},
else => @compileError("Single '}' encountered in format string"),
},
}
}
comptime {
if (args.len != next_arg) {
@compileError("Unused arguments");
}
if (state != State.start) {
@compileError("Incomplete format string: " ++ format);
}
}
if (start_index < format.len) {
try self.write(format[start_index..format.len]);
}
try self.flush();
}
fn write(self: *Writer, value: []const u8) !void {
_ = self;
_ = value;
}
pub fn printValue(self: *Writer, value: anytype) !void {
_ = self;
_ = value;
}
fn flush(self: *Writer) !void {
_ = self;
}
};
{#code_end#}
<p>
This is a proof of concept implementation; the actual function in the standard library has more
formatting capabilities.
</p>
<p>
Note that this is not hard-coded into the Zig compiler; this is userland code in the standard library.
</p>
<p>
When this function is analyzed from our example code above, Zig partially evaluates the function
and emits a function that actually looks like this:
</p>
{#syntax_block|zig|Emitted print Function#}
pub fn print(self: *Writer, arg0: []const u8, arg1: i32) !void {
try self.write("here is a string: '");
try self.printValue(arg0);
try self.write("' here is a number: ");
try self.printValue(arg1);
try self.write("\n");
try self.flush();
}
{#end_syntax_block#}
<p>
{#syntax#}printValue{#endsyntax#} is a function that takes a parameter of any type, and does different things depending
on the type:
</p>
{#code_begin|syntax|poc_printValue_fn#}
const Writer = struct {
pub fn printValue(self: *Writer, value: anytype) !void {
switch (@typeInfo(@TypeOf(value))) {
.Int => {
return self.writeInt(value);
},
.Float => {
return self.writeFloat(value);
},
.Pointer => {
return self.write(value);
},
else => {
@compileError("Unable to print type '" ++ @typeName(@TypeOf(value)) ++ "'");
},
}
}
fn write(self: *Writer, value: []const u8) !void {
_ = self;
_ = value;
}
fn writeInt(self: *Writer, value: anytype) !void {
_ = self;
_ = value;
}
fn writeFloat(self: *Writer, value: anytype) !void {
_ = self;
_ = value;
}
};
{#code_end#}
<p>
And now, what happens if we give too many arguments to {#syntax#}print{#endsyntax#}?
</p>
{#code_begin|test_err|test_print_too_many_args|unused argument in 'here is a string: '{s}' here is a number: {}#}
const print = @import("std").debug.print;
const a_number: i32 = 1234;
const a_string = "foobar";
test "print too many arguments" {
print("here is a string: '{s}' here is a number: {}\n", .{
a_string,
a_number,
a_number,
});
}
{#code_end#}
<p>
Zig gives programmers the tools needed to protect themselves against their own mistakes.
</p>
<p>
Zig doesn't care whether the format argument is a string literal,
only that it is a compile-time known value that can be coerced to a {#syntax#}[]const u8{#endsyntax#}:
</p>
{#code_begin|exe|print_comptime-known_format#}
const print = @import("std").debug.print;
const a_number: i32 = 1234;
const a_string = "foobar";
const fmt = "here is a string: '{s}' here is a number: {}\n";
pub fn main() void {
print(fmt, .{a_string, a_number});
}
{#code_end#}
<p>
This works fine.
</p>
<p>
Zig does not special case string formatting in the compiler and instead exposes enough power to accomplish this
task in userland. It does so without introducing another language on top of Zig, such as
a macro language or a preprocessor language. It's Zig all the way down.
</p>
{#header_close#}
{#see_also|inline while|inline for#}
{#header_close#}
{#header_open|Assembly#}
<p>
For some use cases, it may be necessary to directly control the machine code generated
by Zig programs, rather than relying on Zig's code generation. For these cases, one
can use inline assembly. Here is an example of implementing Hello, World on x86_64 Linux
using inline assembly:
</p>
{#code_begin|exe|inline_assembly#}
{#target_linux_x86_64#}
pub fn main() noreturn {
const msg = "hello world\n";
_ = syscall3(SYS_write, STDOUT_FILENO, @ptrToInt(msg), msg.len);
_ = syscall1(SYS_exit, 0);
unreachable;
}
pub const SYS_write = 1;
pub const SYS_exit = 60;
pub const STDOUT_FILENO = 1;
pub fn syscall1(number: usize, arg1: usize) usize {
return asm volatile ("syscall"
: [ret] "={rax}" (-> usize)
: [number] "{rax}" (number),
[arg1] "{rdi}" (arg1)
: "rcx", "r11"
);
}
pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
return asm volatile ("syscall"
: [ret] "={rax}" (-> usize)
: [number] "{rax}" (number),
[arg1] "{rdi}" (arg1),
[arg2] "{rsi}" (arg2),
[arg3] "{rdx}" (arg3)
: "rcx", "r11"
);
}
{#code_end#}
<p>
Dissecting the syntax:
</p>
{#syntax_block|zig|Assembly Syntax Explained#}
// Inline assembly is an expression which returns a value.
// the `asm` keyword begins the expression.
_ = asm
// `volatile` is an optional modifier that tells Zig this
// inline assembly expression has side-effects. Without
// `volatile`, Zig is allowed to delete the inline assembly
// code if the result is unused.
volatile (
// Next is a comptime string which is the assembly code.
// Inside this string one may use `%[ret]`, `%[number]`,
// or `%[arg1]` where a register is expected, to specify
// the register that Zig uses for the argument or return value,
// if the register constraint strings are used. However in
// the below code, this is not used. A literal `%` can be
// obtained by escaping it with a double percent: `%%`.
// Often multiline string syntax comes in handy here.
\\syscall
// Next is the output. It is possible in the future Zig will
// support multiple outputs, depending on how
// https://github.com/ziglang/zig/issues/215 is resolved.
// It is allowed for there to be no outputs, in which case
// this colon would be directly followed by the colon for the inputs.
:
// This specifies the name to be used in `%[ret]` syntax in
// the above assembly string. This example does not use it,
// but the syntax is mandatory.
[ret]
// Next is the output constraint string. This feature is still
// considered unstable in Zig, and so LLVM/GCC documentation
// must be used to understand the semantics.
// http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string
// https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
// In this example, the constraint string means "the result value of
// this inline assembly instruction is whatever is in $rax".
"={rax}"
// Next is either a value binding, or `->` and then a type. The
// type is the result type of the inline assembly expression.
// If it is a value binding, then `%[ret]` syntax would be used
// to refer to the register bound to the value.
(-> usize)
// Next is the list of inputs.
// The constraint for these inputs means, "when the assembly code is
// executed, $rax shall have the value of `number` and $rdi shall have
// the value of `arg1`". Any number of input parameters is allowed,
// including none.
: [number] "{rax}" (number),
[arg1] "{rdi}" (arg1)
// Next is the list of clobbers. These declare a set of registers whose
// values will not be preserved by the execution of this assembly code.
// These do not include output or input registers. The special clobber
// value of "memory" means that the assembly writes to arbitrary undeclared
// memory locations - not only the memory pointed to by a declared indirect
// output. In this example we list $rcx and $r11 because it is known the
// kernel syscall does not preserve these registers.
: "rcx", "r11"
);
{#end_syntax_block#}
<p>
For x86 and x86_64 targets, the syntax is AT&T syntax, rather than the more
popular Intel syntax. This is due to technical constraints; assembly parsing is
provided by LLVM and its support for Intel syntax is buggy and not well tested.
</p>
<p>
Some day Zig may have its own assembler. This would allow it to integrate more seamlessly
into the language, as well as be compatible with the popular NASM syntax. This documentation
section will be updated before 1.0.0 is released, with a conclusive statement about the status
of AT&T vs Intel/NASM syntax.
</p>
{#header_open|Output Constraints#}
<p>
Output constraints are still considered to be unstable in Zig, and
so
<a href="http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string">LLVM documentation</a>
and
<a href="https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html">GCC documentation</a>
must be used to understand the semantics.
</p>
<p>
Note that some breaking changes to output constraints are planned with
<a href="https://github.com/ziglang/zig/issues/215">issue #215</a>.
</p>
{#header_close#}
{#header_open|Input Constraints#}
<p>
Input constraints are still considered to be unstable in Zig, and
so
<a href="http://releases.llvm.org/10.0.0/docs/LangRef.html#inline-asm-constraint-string">LLVM documentation</a>
and
<a href="https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html">GCC documentation</a>
must be used to understand the semantics.
</p>
<p>
Note that some breaking changes to input constraints are planned with
<a href="https://github.com/ziglang/zig/issues/215">issue #215</a>.
</p>
{#header_close#}
{#header_open|Clobbers#}
<p>
Clobbers are the set of registers whose values will not be preserved by the execution of
the assembly code. These do not include output or input registers. The special clobber
value of {#syntax#}"memory"{#endsyntax#} means that the assembly causes writes to
arbitrary undeclared memory locations - not only the memory pointed to by a declared
indirect output.
</p>
<p>
Failure to declare the full set of clobbers for a given inline assembly
expression is unchecked {#link|Undefined Behavior#}.
</p>
{#header_close#}
{#header_open|Global Assembly#}
<p>
When an assembly expression occurs in a {#link|container|Containers#} level {#link|comptime#} block, this is
<strong>global assembly</strong>.
</p>
<p>
This kind of assembly has different rules than inline assembly. First, {#syntax#}volatile{#endsyntax#}
is not valid because all global assembly is unconditionally included.
Second, there are no inputs, outputs, or clobbers. All global assembly is concatenated
verbatim into one long string and assembled together. There are no template substitution rules regarding
<code>%</code> as there are in inline assembly expressions.
</p>
{#code_begin|test|test_global_assembly#}
{#target_linux_x86_64#}
const std = @import("std");
const expect = std.testing.expect;
comptime {
asm (
\\.global my_func;
\\.type my_func, @function;
\\my_func:
\\ lea (%rdi,%rsi,1),%eax
\\ retq
);
}
extern fn my_func(a: i32, b: i32) i32;
test "global assembly" {
try expect(my_func(12, 34) == 46);
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Atomics#}
<p>TODO: @fence()</p>
<p>TODO: @atomic rmw</p>
<p>TODO: builtin atomic memory ordering enum</p>
{#header_close#}
{#header_open|Async Functions#}
<p>Async functions are being temporarily regressed and will be
<a href="https://github.com/ziglang/zig/issues/6025">restored before Zig
0.11.0 is tagged</a>. I apologize for the instability. Please use Zig 0.10.0 with
the <code>-fstage1</code> flag for now if you need this feature.</p>
{#header_close#}
{#header_open|Builtin Functions|2col#}
<p>
Builtin functions are provided by the compiler and are prefixed with <code>@</code>.
The {#syntax#}comptime{#endsyntax#} keyword on a parameter means that the parameter must be known
at compile time.
</p>
{#header_open|@addrSpaceCast#}
<pre>{#syntax#}@addrSpaceCast(comptime addrspace: std.builtin.AddressSpace, ptr: anytype) anytype{#endsyntax#}</pre>
<p>
Converts a pointer from one address space to another. Depending on the current target and
address spaces, this cast may be a no-op, a complex operation, or illegal. If the cast is
legal, then the resulting pointer points to the same memory location as the pointer operand.
It is always valid to cast a pointer between the same address spaces.
</p>
{#header_close#}
{#header_open|@addWithOverflow#}
<pre>{#syntax#}@addWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 }{#endsyntax#}</pre>
<p>
Performs {#syntax#}a + b{#endsyntax#} and returns a tuple with the result and a possible overflow bit.
</p>
{#header_close#}
{#header_open|@alignCast#}
<pre>{#syntax#}@alignCast(comptime alignment: u29, ptr: anytype) anytype{#endsyntax#}</pre>
<p>
{#syntax#}ptr{#endsyntax#} can be {#syntax#}*T{#endsyntax#}, {#syntax#}?*T{#endsyntax#}, or {#syntax#}[]T{#endsyntax#}.
It returns the same type as {#syntax#}ptr{#endsyntax#} except with the alignment adjusted to the new value.
</p>
<p>A {#link|pointer alignment safety check|Incorrect Pointer Alignment#} is added
to the generated code to make sure the pointer is aligned as promised.</p>
{#header_close#}
{#header_open|@alignOf#}
<pre>{#syntax#}@alignOf(comptime T: type) comptime_int{#endsyntax#}</pre>
<p>
This function returns the number of bytes that this type should be aligned to
for the current target to match the C ABI. When the child type of a pointer has
this alignment, the alignment can be omitted from the type.
</p>
<pre>{#syntax#}const assert = @import("std").debug.assert;
comptime {
assert(*u32 == *align(@alignOf(u32)) u32);
}{#endsyntax#}</pre>
<p>
The result is a target-specific compile time constant. It is guaranteed to be
less than or equal to {#link|@sizeOf(T)|@sizeOf#}.
</p>
{#see_also|Alignment#}
{#header_close#}
{#header_open|@as#}
<pre>{#syntax#}@as(comptime T: type, expression) T{#endsyntax#}</pre>
<p>
Performs {#link|Type Coercion#}. This cast is allowed when the conversion is unambiguous and safe,
and is the preferred way to convert between types, whenever possible.
</p>
{#header_close#}
{#header_open|@atomicLoad#}
<pre>{#syntax#}@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T{#endsyntax#}</pre>
<p>
This builtin function atomically dereferences a pointer and returns the value.
</p>
<p>
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
an integer or an enum.
</p>
{#see_also|@atomicStore|@atomicRmw|@fence|@cmpxchgWeak|@cmpxchgStrong#}
{#header_close#}
{#header_open|@atomicRmw#}
<pre>{#syntax#}@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T{#endsyntax#}</pre>
<p>
This builtin function atomically modifies memory and then returns the previous value.
</p>
<p>
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
an integer or an enum.
</p>
<p>
Supported operations:
</p>
<ul>
<li>{#syntax#}.Xchg{#endsyntax#} - stores the operand unmodified. Supports enums, integers and floats.</li>
<li>{#syntax#}.Add{#endsyntax#} - for integers, twos complement wraparound addition.
Also supports {#link|Floats#}.</li>
<li>{#syntax#}.Sub{#endsyntax#} - for integers, twos complement wraparound subtraction.
Also supports {#link|Floats#}.</li>
<li>{#syntax#}.And{#endsyntax#} - bitwise and</li>
<li>{#syntax#}.Nand{#endsyntax#} - bitwise nand</li>
<li>{#syntax#}.Or{#endsyntax#} - bitwise or</li>
<li>{#syntax#}.Xor{#endsyntax#} - bitwise xor</li>
<li>{#syntax#}.Max{#endsyntax#} - stores the operand if it is larger. Supports integers and floats.</li>
<li>{#syntax#}.Min{#endsyntax#} - stores the operand if it is smaller. Supports integers and floats.</li>
</ul>
{#see_also|@atomicStore|@atomicLoad|@fence|@cmpxchgWeak|@cmpxchgStrong#}
{#header_close#}
{#header_open|@atomicStore#}
<pre>{#syntax#}@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: builtin.AtomicOrder) void{#endsyntax#}</pre>
<p>
This builtin function atomically stores a value.
</p>
<p>
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
an integer or an enum.
</p>
{#see_also|@atomicLoad|@atomicRmw|@fence|@cmpxchgWeak|@cmpxchgStrong#}
{#header_close#}
{#header_open|@bitCast#}
<pre>{#syntax#}@bitCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}</pre>
<p>
Converts a value of one type to another type.
</p>
<p>
Asserts that {#syntax#}@sizeOf(@TypeOf(value)) == @sizeOf(DestType){#endsyntax#}.
</p>
<p>
Asserts that {#syntax#}@typeInfo(DestType) != .Pointer{#endsyntax#}. Use {#syntax#}@ptrCast{#endsyntax#} or {#syntax#}@intToPtr{#endsyntax#} if you need this.
</p>
<p>
Can be used for these things for example:
</p>
<ul>
<li>Convert {#syntax#}f32{#endsyntax#} to {#syntax#}u32{#endsyntax#} bits</li>
<li>Convert {#syntax#}i32{#endsyntax#} to {#syntax#}u32{#endsyntax#} preserving twos complement</li>
</ul>
<p>
Works at compile-time if {#syntax#}value{#endsyntax#} is known at compile time. It's a compile error to bitcast a value of undefined layout; this means that, besides the restriction from types which possess dedicated casting builtins (enums, pointers, error sets), bare structs, error unions, slices, optionals, and any other type without a well-defined memory layout, also cannot be used in this operation.
</p>
{#header_close#}
{#header_open|@bitOffsetOf#}
<pre>{#syntax#}@bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}</pre>
<p>
Returns the bit offset of a field relative to its containing struct.
</p>
<p>
For non {#link|packed structs|packed struct#}, this will always be divisible by {#syntax#}8{#endsyntax#}.
For packed structs, non-byte-aligned fields will share a byte offset, but they will have different
bit offsets.
</p>
{#see_also|@offsetOf#}
{#header_close#}
{#header_open|@boolToInt#}
<pre>{#syntax#}@boolToInt(value: bool) u1{#endsyntax#}</pre>
<p>
Converts {#syntax#}true{#endsyntax#} to {#syntax#}@as(u1, 1){#endsyntax#} and {#syntax#}false{#endsyntax#} to
{#syntax#}@as(u1, 0){#endsyntax#}.
</p>
<p>
If the value is known at compile-time, the return type is {#syntax#}comptime_int{#endsyntax#}
instead of {#syntax#}u1{#endsyntax#}.
</p>
{#header_close#}
{#header_open|@bitSizeOf#}
<pre>{#syntax#}@bitSizeOf(comptime T: type) comptime_int{#endsyntax#}</pre>
<p>
This function returns the number of bits it takes to store {#syntax#}T{#endsyntax#} in memory if the type
were a field in a packed struct/union.
The result is a target-specific compile time constant.
</p>
<p>
This function measures the size at runtime. For types that are disallowed at runtime, such as
{#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}.
</p>
{#see_also|@sizeOf|@typeInfo#}
{#header_close#}
{#header_open|@breakpoint#}
<pre>{#syntax#}@breakpoint(){#endsyntax#}</pre>
<p>
This function inserts a platform-specific debug trap instruction which causes
debuggers to break there.
</p>
<p>
This function is only valid within function scope.
</p>
{#header_close#}
{#header_open|@mulAdd#}
<pre>{#syntax#}@mulAdd(comptime T: type, a: T, b: T, c: T) T{#endsyntax#}</pre>
<p>
Fused multiply-add, similar to {#syntax#}(a * b) + c{#endsyntax#}, except
only rounds once, and is thus more accurate.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats.
</p>
{#header_close#}
{#header_open|@byteSwap#}
<pre>{#syntax#}@byteSwap(operand: anytype) T{#endsyntax#}</pre>
<p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type with bit count evenly divisible by 8.</p>
<p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p>
<p>
Swaps the byte order of the integer. This converts a big endian integer to a little endian integer,
and converts a little endian integer to a big endian integer.
</p>
<p>
Note that for the purposes of memory layout with respect to endianness, the integer type should be
related to the number of bytes reported by {#link|@sizeOf#} bytes. This is demonstrated with
{#syntax#}u24{#endsyntax#}. {#syntax#}@sizeOf(u24) == 4{#endsyntax#}, which means that a
{#syntax#}u24{#endsyntax#} stored in memory takes 4 bytes, and those 4 bytes are what are swapped on
a little vs big endian system. On the other hand, if {#syntax#}T{#endsyntax#} is specified to
be {#syntax#}u24{#endsyntax#}, then only 3 bytes are reversed.
</p>
{#header_close#}
{#header_open|@bitReverse#}
<pre>{#syntax#}@bitReverse(integer: anytype) T{#endsyntax#}</pre>
<p>{#syntax#}@TypeOf(anytype){#endsyntax#} accepts any integer type or integer vector type.</p>
<p>
Reverses the bitpattern of an integer value, including the sign bit if applicable.
</p>
<p>
For example 0b10110110 ({#syntax#}u8 = 182{#endsyntax#}, {#syntax#}i8 = -74{#endsyntax#})
becomes 0b01101101 ({#syntax#}u8 = 109{#endsyntax#}, {#syntax#}i8 = 109{#endsyntax#}).
</p>
{#header_close#}
{#header_open|@offsetOf#}
<pre>{#syntax#}@offsetOf(comptime T: type, comptime field_name: []const u8) comptime_int{#endsyntax#}</pre>
<p>
Returns the byte offset of a field relative to its containing struct.
</p>
{#see_also|@bitOffsetOf#}
{#header_close#}
{#header_open|@call#}
<pre>{#syntax#}@call(modifier: std.builtin.CallModifier, function: anytype, args: anytype) anytype{#endsyntax#}</pre>
<p>
Calls a function, in the same way that invoking an expression with parentheses does:
</p>
{#code_begin|test|test_call_builtin#}
const expect = @import("std").testing.expect;
test "noinline function call" {
try expect(@call(.auto, add, .{3, 9}) == 12);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
{#code_end#}
<p>
{#syntax#}@call{#endsyntax#} allows more flexibility than normal function call syntax does. The
{#syntax#}CallModifier{#endsyntax#} enum is reproduced here:
</p>
{#syntax_block|zig|builtin.CallModifier struct#}
pub const CallModifier = enum {
/// Equivalent to function call syntax.
auto,
/// Equivalent to async keyword used with function call syntax.
async_kw,
/// Prevents tail call optimization. This guarantees that the return
/// address will point to the callsite, as opposed to the callsite's
/// callsite. If the call is otherwise required to be tail-called
/// or inlined, a compile error is emitted instead.
never_tail,
/// Guarantees that the call will not be inlined. If the call is
/// otherwise required to be inlined, a compile error is emitted instead.
never_inline,
/// Asserts that the function call will not suspend. This allows a
/// non-async function to call an async function.
no_async,
/// Guarantees that the call will be generated with tail call optimization.
/// If this is not possible, a compile error is emitted instead.
always_tail,
/// Guarantees that the call will inlined at the callsite.
/// If this is not possible, a compile error is emitted instead.
always_inline,
/// Evaluates the call at compile-time. If the call cannot be completed at
/// compile-time, a compile error is emitted instead.
compile_time,
};
{#end_syntax_block#}
{#header_close#}
{#header_open|@cDefine#}
<pre>{#syntax#}@cDefine(comptime name: []u8, value){#endsyntax#}</pre>
<p>
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
</p>
<p>
This appends <code>#define $name $value</code> to the {#syntax#}@cImport{#endsyntax#}
temporary buffer.
</p>
<p>
To define without a value, like this:
</p>
<pre><code class="c">#define _GNU_SOURCE</code></pre>
<p>
Use the void value, like this:
</p>
<pre>{#syntax#}@cDefine("_GNU_SOURCE", {}){#endsyntax#}</pre>
{#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#}
{#header_close#}
{#header_open|@cImport#}
<pre>{#syntax#}@cImport(expression) type{#endsyntax#}</pre>
<p>
This function parses C code and imports the functions, types, variables,
and compatible macro definitions into a new empty struct type, and then
returns that type.
</p>
<p>
{#syntax#}expression{#endsyntax#} is interpreted at compile time. The builtin functions
{#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#} work
within this expression, appending to a temporary buffer which is then parsed as C code.
</p>
<p>
Usually you should only have one {#syntax#}@cImport{#endsyntax#} in your entire application, because it saves the compiler
from invoking clang multiple times, and prevents inline functions from being duplicated.
</p>
<p>
Reasons for having multiple {#syntax#}@cImport{#endsyntax#} expressions would be:
</p>
<ul>
<li>To avoid a symbol collision, for example if foo.h and bar.h both <code>#define CONNECTION_COUNT</code></li>
<li>To analyze the C code with different preprocessor defines</li>
</ul>
{#see_also|Import from C Header File|@cInclude|@cDefine|@cUndef#}
{#header_close#}
{#header_open|@cInclude#}
<pre>{#syntax#}@cInclude(comptime path: []u8){#endsyntax#}</pre>
<p>
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
</p>
<p>
This appends <code>#include <$path>\n</code> to the {#syntax#}c_import{#endsyntax#}
temporary buffer.
</p>
{#see_also|Import from C Header File|@cImport|@cDefine|@cUndef#}
{#header_close#}
{#header_open|@clz#}
<pre>{#syntax#}@clz(operand: anytype){#endsyntax#}</pre>
<p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.</p>
<p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p>
<p>
This function counts the number of most-significant (leading in a big-Endian sense) zeroes in an integer.
</p>
<p>
If {#syntax#}operand{#endsyntax#} is a {#link|comptime#}-known integer,
the return type is {#syntax#}comptime_int{#endsyntax#}.
Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number
of bits that can represent the bit count of the integer type.
</p>
<p>
If {#syntax#}operand{#endsyntax#} is zero, {#syntax#}@clz{#endsyntax#} returns the bit width
of integer type {#syntax#}T{#endsyntax#}.
</p>
{#see_also|@ctz|@popCount#}
{#header_close#}
{#header_open|@cmpxchgStrong#}
<pre>{#syntax#}@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}</pre>
<p>
This function performs a strong atomic compare exchange operation. It's the equivalent of this code,
except atomic:
</p>
{#code_begin|syntax|not_atomic_cmpxchgStrong#}
fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
const old_value = ptr.*;
if (old_value == expected_value) {
ptr.* = new_value;
return null;
} else {
return old_value;
}
}
{#code_end#}
<p>
If you are using cmpxchg in a loop, {#link|@cmpxchgWeak#} is the better choice, because it can be implemented
more efficiently in machine instructions.
</p>
<p>
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
an integer or an enum.
</p>
<p>{#syntax#}@typeInfo(@TypeOf(ptr)).Pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>
{#see_also|@atomicStore|@atomicLoad|@atomicRmw|@fence|@cmpxchgWeak#}
{#header_close#}
{#header_open|@cmpxchgWeak#}
<pre>{#syntax#}@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T{#endsyntax#}</pre>
<p>
This function performs a weak atomic compare exchange operation. It's the equivalent of this code,
except atomic:
</p>
{#syntax_block|zig|cmpxchgWeakButNotAtomic#}
fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
const old_value = ptr.*;
if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
ptr.* = new_value;
return null;
} else {
return old_value;
}
}
{#end_syntax_block#}
<p>
If you are using cmpxchg in a loop, the sporadic failure will be no problem, and {#syntax#}cmpxchgWeak{#endsyntax#}
is the better choice, because it can be implemented more efficiently in machine instructions.
However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}.
</p>
<p>
{#syntax#}T{#endsyntax#} must be a pointer, a {#syntax#}bool{#endsyntax#}, a float,
an integer or an enum.
</p>
<p>{#syntax#}@typeInfo(@TypeOf(ptr)).Pointer.alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>
{#see_also|@atomicStore|@atomicLoad|@atomicRmw|@fence|@cmpxchgStrong#}
{#header_close#}
{#header_open|@compileError#}
<pre>{#syntax#}@compileError(comptime msg: []u8){#endsyntax#}</pre>
<p>
This function, when semantically analyzed, causes a compile error with the
message {#syntax#}msg{#endsyntax#}.
</p>
<p>
There are several ways that code avoids being semantically checked, such as
using {#syntax#}if{#endsyntax#} or {#syntax#}switch{#endsyntax#} with compile time constants,
and {#syntax#}comptime{#endsyntax#} functions.
</p>
{#header_close#}
{#header_open|@compileLog#}
<pre>{#syntax#}@compileLog(args: ...){#endsyntax#}</pre>
<p>
This function prints the arguments passed to it at compile-time.
</p>
<p>
To prevent accidentally leaving compile log statements in a codebase,
a compilation error is added to the build, pointing to the compile
log statement. This error prevents code from being generated, but
does not otherwise interfere with analysis.
</p>
<p>
This function can be used to do "printf debugging" on
compile-time executing code.
</p>
{#code_begin|test_err|test_compileLog_builtin|found compile log statement#}
const print = @import("std").debug.print;
const num1 = blk: {
var val1: i32 = 99;
@compileLog("comptime val1 = ", val1);
val1 = val1 + 1;
break :blk val1;
};
test "main" {
@compileLog("comptime in main");
print("Runtime in main, num1 = {}.\n", .{num1});
}
{#code_end#}
<p>
If all {#syntax#}@compileLog{#endsyntax#} calls are removed or
not encountered by analysis, the
program compiles successfully and the generated executable prints:
</p>
{#code_begin|test|test_without_compileLog_builtin#}
const print = @import("std").debug.print;
const num1 = blk: {
var val1: i32 = 99;
val1 = val1 + 1;
break :blk val1;
};
test "main" {
print("Runtime in main, num1 = {}.\n", .{num1});
}
{#code_end#}
{#header_close#}
{#header_open|@ctz#}
<pre>{#syntax#}@ctz(operand: anytype){#endsyntax#}</pre>
<p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.</p>
<p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p>
<p>
This function counts the number of least-significant (trailing in a big-Endian sense) zeroes in an integer.
</p>
<p>
If {#syntax#}operand{#endsyntax#} is a {#link|comptime#}-known integer,
the return type is {#syntax#}comptime_int{#endsyntax#}.
Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number
of bits that can represent the bit count of the integer type.
</p>
<p>
If {#syntax#}operand{#endsyntax#} is zero, {#syntax#}@ctz{#endsyntax#} returns
the bit width of integer type {#syntax#}T{#endsyntax#}.
</p>
{#see_also|@clz|@popCount#}
{#header_close#}
{#header_open|@cUndef#}
<pre>{#syntax#}@cUndef(comptime name: []u8){#endsyntax#}</pre>
<p>
This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
</p>
<p>
This appends <code>#undef $name</code> to the {#syntax#}@cImport{#endsyntax#}
temporary buffer.
</p>
{#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#}
{#header_close#}
{#header_open|@cVaArg#}
<pre>{#syntax#}@cVaArg(operand: *std.builtin.VaList, comptime T: type) T{#endsyntax#}</pre>
<p>
Implements the C macro {#syntax#}va_arg{#endsyntax#}.
</p>
{#see_also|@cVaCopy|@cVaEnd|@cVaStart#}
{#header_close#}
{#header_open|@cVaCopy#}
<pre>{#syntax#}@cVaCopy(src: *std.builtin.VaList) std.builtin.VaList{#endsyntax#}</pre>
<p>
Implements the C macro {#syntax#}va_copy{#endsyntax#}.
</p>
{#see_also|@cVaArg|@cVaEnd|@cVaStart#}
{#header_close#}
{#header_open|@cVaEnd#}
<pre>{#syntax#}@cVaEnd(src: *std.builtin.VaList) void{#endsyntax#}</pre>
<p>
Implements the C macro {#syntax#}va_end{#endsyntax#}.
</p>
{#see_also|@cVaArg|@cVaCopy|@cVaStart#}
{#header_close#}
{#header_open|@cVaStart#}
<pre>{#syntax#}@cVaStart() std.builtin.VaList{#endsyntax#}</pre>
<p>
Implements the C macro {#syntax#}va_start{#endsyntax#}. Only valid inside a variadic function.
</p>
{#see_also|@cVaArg|@cVaCopy|@cVaEnd#}
{#header_close#}
{#header_open|@divExact#}
<pre>{#syntax#}@divExact(numerator: T, denominator: T) T{#endsyntax#}</pre>
<p>
Exact division. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and
{#syntax#}@divTrunc(numerator, denominator) * denominator == numerator{#endsyntax#}.
</p>
<ul>
<li>{#syntax#}@divExact(6, 3) == 2{#endsyntax#}</li>
<li>{#syntax#}@divExact(a, b) * b == a{#endsyntax#}</li>
</ul>
<p>For a function that returns a possible error code, use {#syntax#}@import("std").math.divExact{#endsyntax#}.</p>
{#see_also|@divTrunc|@divFloor#}
{#header_close#}
{#header_open|@divFloor#}
<pre>{#syntax#}@divFloor(numerator: T, denominator: T) T{#endsyntax#}</pre>
<p>
Floored division. Rounds toward negative infinity. For unsigned integers it is
the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and
{#syntax#}!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}.
</p>
<ul>
<li>{#syntax#}@divFloor(-5, 3) == -2{#endsyntax#}</li>
<li>{#syntax#}(@divFloor(a, b) * b) + @mod(a, b) == a{#endsyntax#}</li>
</ul>
<p>For a function that returns a possible error code, use {#syntax#}@import("std").math.divFloor{#endsyntax#}.</p>
{#see_also|@divTrunc|@divExact#}
{#header_close#}
{#header_open|@divTrunc#}
<pre>{#syntax#}@divTrunc(numerator: T, denominator: T) T{#endsyntax#}</pre>
<p>
Truncated division. Rounds toward zero. For unsigned integers it is
the same as {#syntax#}numerator / denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator != 0{#endsyntax#} and
{#syntax#}!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1){#endsyntax#}.
</p>
<ul>
<li>{#syntax#}@divTrunc(-5, 3) == -1{#endsyntax#}</li>
<li>{#syntax#}(@divTrunc(a, b) * b) + @rem(a, b) == a{#endsyntax#}</li>
</ul>
<p>For a function that returns a possible error code, use {#syntax#}@import("std").math.divTrunc{#endsyntax#}.</p>
{#see_also|@divFloor|@divExact#}
{#header_close#}
{#header_open|@embedFile#}
<pre>{#syntax#}@embedFile(comptime path: []const u8) *const [N:0]u8{#endsyntax#}</pre>
<p>
This function returns a compile time constant pointer to null-terminated,
fixed-size array with length equal to the byte count of the file given by
{#syntax#}path{#endsyntax#}. The contents of the array are the contents of the file.
This is equivalent to a {#link|string literal|String Literals and Unicode Code Point Literals#}
with the file contents.
</p>
<p>
{#syntax#}path{#endsyntax#} is absolute or relative to the current file, just like {#syntax#}@import{#endsyntax#}.
</p>
{#see_also|@import#}
{#header_close#}
{#header_open|@enumToInt#}
<pre>{#syntax#}@enumToInt(enum_or_tagged_union: anytype) anytype{#endsyntax#}</pre>
<p>
Converts an enumeration value into its integer tag type. When a tagged union is passed,
the tag value is used as the enumeration value.
</p>
<p>
If there is only one possible enum value, the result is a {#syntax#}comptime_int{#endsyntax#}
known at {#link|comptime#}.
</p>
{#see_also|@intToEnum#}
{#header_close#}
{#header_open|@errorName#}
<pre>{#syntax#}@errorName(err: anyerror) [:0]const u8{#endsyntax#}</pre>
<p>
This function returns the string representation of an error. The string representation
of {#syntax#}error.OutOfMem{#endsyntax#} is {#syntax#}"OutOfMem"{#endsyntax#}.
</p>
<p>
If there are no calls to {#syntax#}@errorName{#endsyntax#} in an entire application,
or all calls have a compile-time known value for {#syntax#}err{#endsyntax#}, then no
error name table will be generated.
</p>
{#header_close#}
{#header_open|@errorReturnTrace#}
<pre>{#syntax#}@errorReturnTrace() ?*builtin.StackTrace{#endsyntax#}</pre>
<p>
If the binary is built with error return tracing, and this function is invoked in a
function that calls a function with an error or error union return type, returns a
stack trace object. Otherwise returns {#link|null#}.
</p>
{#header_close#}
{#header_open|@errorToInt#}
<pre>{#syntax#}@errorToInt(err: anytype) std.meta.Int(.unsigned, @sizeOf(anyerror) * 8){#endsyntax#}</pre>
<p>
Supports the following types:
</p>
<ul>
<li>{#link|The Global Error Set#}</li>
<li>{#link|Error Set Type#}</li>
<li>{#link|Error Union Type#}</li>
</ul>
<p>
Converts an error to the integer representation of an error.
</p>
<p>
It is generally recommended to avoid this
cast, as the integer representation of an error is not stable across source code changes.
</p>
{#see_also|@intToError#}
{#header_close#}
{#header_open|@errSetCast#}
<pre>{#syntax#}@errSetCast(comptime T: DestType, value: anytype) DestType{#endsyntax#}</pre>
<p>
Converts an error value from one error set to another error set. Attempting to convert an error
which is not in the destination error set results in safety-protected {#link|Undefined Behavior#}.
</p>
{#header_close#}
{#header_open|@export#}
<pre>{#syntax#}@export(declaration, comptime options: std.builtin.ExportOptions) void{#endsyntax#}</pre>
<p>
Creates a symbol in the output object file.
</p>
<p>
<code>declaration</code> must be one of two things:
</p>
<ul>
<li>An identifier ({#syntax#}x{#endsyntax#}) identifying a {#link|function|Functions#} or a
{#link|variable|Container Level Variables#}.</li>
<li>Field access ({#syntax#}x.y{#endsyntax#}) looking up a {#link|function|Functions#} or a
{#link|variable|Container Level Variables#}.</li>
</ul>
<p>
This builtin can be called from a {#link|comptime#} block to conditionally export symbols.
When <code>declaration</code> is a function with the C calling convention and
{#syntax#}options.linkage{#endsyntax#} is {#syntax#}Strong{#endsyntax#}, this is equivalent to
the {#syntax#}export{#endsyntax#} keyword used on a function:
</p>
{#code_begin|obj|export_builtin#}
comptime {
@export(internalName, .{ .name = "foo", .linkage = .Strong });
}
fn internalName() callconv(.C) void {}
{#code_end#}
<p>This is equivalent to:</p>
{#code_begin|obj|export_builtin_equivalent_code#}
export fn foo() void {}
{#code_end#}
<p>Note that even when using {#syntax#}export{#endsyntax#}, the {#syntax#}@"foo"{#endsyntax#} syntax for
{#link|identifiers|Identifiers#} can be used to choose any string for the symbol name:</p>
{#code_begin|obj|export_any_symbol_name#}
export fn @"A function name that is a complete sentence."() void {}
{#code_end#}
<p>
When looking at the resulting object, you can see the symbol is used verbatim:
</p>
<pre><code>00000000000001f0 T A function name that is a complete sentence.</code></pre>
{#see_also|Exporting a C Library#}
{#header_close#}
{#header_open|@extern#}
<pre>{#syntax#}@extern(T: type, comptime options: std.builtin.ExternOptions) *T{#endsyntax#}</pre>
<p>
Creates a reference to an external symbol in the output object file.
</p>
{#see_also|@export#}
{#header_close#}
{#header_open|@fence#}
<pre>{#syntax#}@fence(order: AtomicOrder){#endsyntax#}</pre>
<p>
The {#syntax#}fence{#endsyntax#} function is used to introduce happens-before edges between operations.
</p>
<p>
{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.
</p>
{#see_also|@atomicStore|@atomicLoad|@atomicRmw|@cmpxchgWeak|@cmpxchgStrong#}
{#header_close#}
{#header_open|@field#}
<pre>{#syntax#}@field(lhs: anytype, comptime field_name: []const u8) (field){#endsyntax#}</pre>
<p>Performs field access by a compile-time string. Works on both fields and declarations.
</p>
{#code_begin|test|test_field_builtin#}
const std = @import("std");
const Point = struct {
x: u32,
y: u32,
pub var z: u32 = 1;
};
test "field access by string" {
const expect = std.testing.expect;
var p = Point{ .x = 0, .y = 0 };
@field(p, "x") = 4;
@field(p, "y") = @field(p, "x") + 1;
try expect(@field(p, "x") == 4);
try expect(@field(p, "y") == 5);
}
test "decl access by string" {
const expect = std.testing.expect;
try expect(@field(Point, "z") == 1);
@field(Point, "z") = 2;
try expect(@field(Point, "z") == 2);
}
{#code_end#}
{#header_close#}
{#header_open|@fieldParentPtr#}
<pre>{#syntax#}@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,
field_ptr: *T) *ParentType{#endsyntax#}</pre>
<p>
Given a pointer to a field, returns the base pointer of a struct.
</p>
{#header_close#}
{#header_open|@floatCast#}
<pre>{#syntax#}@floatCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}</pre>
<p>
Convert from one float type to another. This cast is safe, but may cause the
numeric value to lose precision.
</p>
{#header_close#}
{#header_open|@floatToInt#}
<pre>{#syntax#}@floatToInt(comptime DestType: type, float: anytype) DestType{#endsyntax#}</pre>
<p>
Converts the integer part of a floating point number to the destination type.
</p>
<p>
If the integer part of the floating point number cannot fit in the destination type,
it invokes safety-checked {#link|Undefined Behavior#}.
</p>
{#see_also|@intToFloat#}
{#header_close#}
{#header_open|@frameAddress#}
<pre>{#syntax#}@frameAddress() usize{#endsyntax#}</pre>
<p>
This function returns the base pointer of the current stack frame.
</p>
<p>
The implications of this are target-specific and not consistent across all
platforms. The frame address may not be available in release mode due to
aggressive optimizations.
</p>
<p>
This function is only valid within function scope.
</p>
{#header_close#}
{#header_open|@hasDecl#}
<pre>{#syntax#}@hasDecl(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}</pre>
<p>
Returns whether or not a {#link|container|Containers#} has a declaration
matching {#syntax#}name{#endsyntax#}.
</p>
{#code_begin|test|test_hasDecl_builtin#}
const std = @import("std");
const expect = std.testing.expect;
const Foo = struct {
nope: i32,
pub var blah = "xxx";
const hi = 1;
};
test "@hasDecl" {
try expect(@hasDecl(Foo, "blah"));
// Even though `hi` is private, @hasDecl returns true because this test is
// in the same file scope as Foo. It would return false if Foo was declared
// in a different file.
try expect(@hasDecl(Foo, "hi"));
// @hasDecl is for declarations; not fields.
try expect(!@hasDecl(Foo, "nope"));
try expect(!@hasDecl(Foo, "nope1234"));
}
{#code_end#}
{#see_also|@hasField#}
{#header_close#}
{#header_open|@hasField#}
<pre>{#syntax#}@hasField(comptime Container: type, comptime name: []const u8) bool{#endsyntax#}</pre>
<p>Returns whether the field name of a struct, union, or enum exists.</p>
<p>
The result is a compile time constant.
</p>
<p>
It does not include functions, variables, or constants.
</p>
{#see_also|@hasDecl#}
{#header_close#}
{#header_open|@import#}
<pre>{#syntax#}@import(comptime path: []u8) type{#endsyntax#}</pre>
<p>
This function finds a zig file corresponding to {#syntax#}path{#endsyntax#} and adds it to the build,
if it is not already added.
</p>
<p>
Zig source files are implicitly structs, with a name equal to the file's basename with the extension
truncated. {#syntax#}@import{#endsyntax#} returns the struct type corresponding to the file.
</p>
<p>
Declarations which have the {#syntax#}pub{#endsyntax#} keyword may be referenced from a different
source file than the one they are declared in.
</p>
<p>
{#syntax#}path{#endsyntax#} can be a relative path or it can be the name of a package.
If it is a relative path, it is relative to the file that contains the {#syntax#}@import{#endsyntax#}
function call.
</p>
<p>
The following packages are always available:
</p>
<ul>
<li>{#syntax#}@import("std"){#endsyntax#} - Zig Standard Library</li>
<li>{#syntax#}@import("builtin"){#endsyntax#} - Target-specific information.
The command <code>zig build-exe --show-builtin</code> outputs the source to stdout for reference.
</li>
<li>{#syntax#}@import("root"){#endsyntax#} - Points to the root source file.
This is usually <code>src/main.zig</code> but it depends on what file is chosen to be built.
</li>
</ul>
{#see_also|Compile Variables|@embedFile#}
{#header_close#}
{#header_open|@intCast#}
<pre>{#syntax#}@intCast(comptime DestType: type, int: anytype) DestType{#endsyntax#}</pre>
<p>
Converts an integer to another integer while keeping the same numerical value.
Attempting to convert a number which is out of range of the destination type results in
safety-protected {#link|Undefined Behavior#}.
</p>
{#code_begin|test_err|test_intCast_builtin|cast truncated bits#}
test "integer cast panic" {
var a: u16 = 0xabcd;
var b: u8 = @intCast(u8, a);
_ = b;
}
{#code_end#}
<p>
To truncate the significant bits of a number out of range of the destination type, use {#link|@truncate#}.
</p>
<p>
If {#syntax#}T{#endsyntax#} is {#syntax#}comptime_int{#endsyntax#},
then this is semantically equivalent to {#link|Type Coercion#}.
</p>
{#header_close#}
{#header_open|@intToEnum#}
<pre>{#syntax#}@intToEnum(comptime DestType: type, integer: anytype) DestType{#endsyntax#}</pre>
<p>
Converts an integer into an {#link|enum#} value.
</p>
<p>
Attempting to convert an integer which represents no value in the chosen enum type invokes
safety-checked {#link|Undefined Behavior#}.
</p>
{#see_also|@enumToInt#}
{#header_close#}
{#header_open|@intToError#}
<pre>{#syntax#}@intToError(value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)) anyerror{#endsyntax#}</pre>
<p>
Converts from the integer representation of an error into {#link|The Global Error Set#} type.
</p>
<p>
It is generally recommended to avoid this
cast, as the integer representation of an error is not stable across source code changes.
</p>
<p>
Attempting to convert an integer that does not correspond to any error results in
safety-protected {#link|Undefined Behavior#}.
</p>
{#see_also|@errorToInt#}
{#header_close#}
{#header_open|@intToFloat#}
<pre>{#syntax#}@intToFloat(comptime DestType: type, int: anytype) DestType{#endsyntax#}</pre>
<p>
Converts an integer to the closest floating point representation. To convert the other way, use {#link|@floatToInt#}. This cast is always safe.
</p>
{#header_close#}
{#header_open|@intToPtr#}
<pre>{#syntax#}@intToPtr(comptime DestType: type, address: usize) DestType{#endsyntax#}</pre>
<p>
Converts an integer to a {#link|pointer|Pointers#}. To convert the other way, use {#link|@ptrToInt#}. Casting an address of 0 to a destination type
which in not {#link|optional|Optional Pointers#} and does not have the {#syntax#}allowzero{#endsyntax#} attribute will result in a
{#link|Pointer Cast Invalid Null#} panic when runtime safety checks are enabled.
</p>
<p>
If the destination pointer type does not allow address zero and {#syntax#}address{#endsyntax#}
is zero, this invokes safety-checked {#link|Undefined Behavior#}.
</p>
{#header_close#}
{#header_open|@max#}
<pre>{#syntax#}@max(a: T, b: T) T{#endsyntax#}</pre>
<p>
Returns the maximum value of {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#}. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
</p>
<p>
NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.
</p>
{#see_also|@min|Vectors#}
{#header_close#}
{#header_open|@memcpy#}
<pre>{#syntax#}@memcpy(noalias dest: [*]u8, noalias source: [*]const u8, byte_count: usize){#endsyntax#}</pre>
<p>
This function copies bytes from one region of memory to another. {#syntax#}dest{#endsyntax#} and
{#syntax#}source{#endsyntax#} are both pointers and must not overlap.
</p>
<p>
This function is a low level intrinsic with no safety mechanisms. Most code
should not use this function, instead using something like this:
</p>
<pre>{#syntax#}for (source[0..byte_count]) |b, i| dest[i] = b;{#endsyntax#}</pre>
<p>
The optimizer is intelligent enough to turn the above snippet into a memcpy.
</p>
<p>There is also a standard library function for this:</p>
<pre>{#syntax#}const mem = @import("std").mem;
mem.copy(u8, dest[0..byte_count], source[0..byte_count]);{#endsyntax#}</pre>
{#header_close#}
{#header_open|@memset#}
<pre>{#syntax#}@memset(dest: [*]u8, c: u8, byte_count: usize){#endsyntax#}</pre>
<p>
This function sets a region of memory to {#syntax#}c{#endsyntax#}. {#syntax#}dest{#endsyntax#} is a pointer.
</p>
<p>
This function is a low level intrinsic with no safety mechanisms. Most
code should not use this function, instead using something like this:
</p>
<pre>{#syntax#}for (dest[0..byte_count]) |*b| b.* = c;{#endsyntax#}</pre>
<p>
The optimizer is intelligent enough to turn the above snippet into a memset.
</p>
<p>There is also a standard library function for this:</p>
<pre>{#syntax#}const mem = @import("std").mem;
mem.set(u8, dest, c);{#endsyntax#}</pre>
{#header_close#}
{#header_open|@min#}
<pre>{#syntax#}@min(a: T, b: T) T{#endsyntax#}</pre>
<p>
Returns the minimum value of {#syntax#}a{#endsyntax#} and {#syntax#}b{#endsyntax#}. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
</p>
<p>
NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.
</p>
{#see_also|@max|Vectors#}
{#header_close#}
{#header_open|@wasmMemorySize#}
<pre>{#syntax#}@wasmMemorySize(index: u32) u32{#endsyntax#}</pre>
<p>
This function returns the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} as
an unsigned value in units of Wasm pages. Note that each Wasm page is 64KB in size.
</p>
<p>
This function is a low level intrinsic with no safety mechanisms usually useful for allocator
designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use
something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}.
</p>
{#see_also|@wasmMemoryGrow#}
{#header_close#}
{#header_open|@wasmMemoryGrow#}
<pre>{#syntax#}@wasmMemoryGrow(index: u32, delta: u32) i32{#endsyntax#}</pre>
<p>
This function increases the size of the Wasm memory identified by {#syntax#}index{#endsyntax#} by
{#syntax#}delta{#endsyntax#} in units of unsigned number of Wasm pages. Note that each Wasm page
is 64KB in size. On success, returns previous memory size; on failure, if the allocation fails,
returns -1.
</p>
<p>
This function is a low level intrinsic with no safety mechanisms usually useful for allocator
designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use
something like {#syntax#}@import("std").heap.WasmPageAllocator{#endsyntax#}.
</p>
{#code_begin|test|test_wasmMemoryGrow_builtin#}
const std = @import("std");
const native_arch = @import("builtin").target.cpu.arch;
const expect = std.testing.expect;
test "@wasmMemoryGrow" {
if (native_arch != .wasm32) return error.SkipZigTest;
var prev = @wasmMemorySize(0);
try expect(prev == @wasmMemoryGrow(0, 1));
try expect(prev + 1 == @wasmMemorySize(0));
}
{#code_end#}
{#see_also|@wasmMemorySize#}
{#header_close#}
{#header_open|@mod#}
<pre>{#syntax#}@mod(numerator: T, denominator: T) T{#endsyntax#}</pre>
<p>
Modulus division. For unsigned integers this is the same as
{#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator > 0{#endsyntax#}, otherwise the
operation will result in a {#link|Remainder Division by Zero#} when runtime safety checks are enabled.
</p>
<ul>
<li>{#syntax#}@mod(-5, 3) == 1{#endsyntax#}</li>
<li>{#syntax#}(@divFloor(a, b) * b) + @mod(a, b) == a{#endsyntax#}</li>
</ul>
<p>For a function that returns an error code, see {#syntax#}@import("std").math.mod{#endsyntax#}.</p>
{#see_also|@rem#}
{#header_close#}
{#header_open|@mulWithOverflow#}
<pre>{#syntax#}@mulWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 }{#endsyntax#}</pre>
<p>
Performs {#syntax#}a * b{#endsyntax#} and returns a tuple with the result and a possible overflow bit.
</p>
{#header_close#}
{#header_open|@panic#}
<pre>{#syntax#}@panic(message: []const u8) noreturn{#endsyntax#}</pre>
<p>
Invokes the panic handler function. By default the panic handler function
calls the public {#syntax#}panic{#endsyntax#} function exposed in the root source file, or
if there is not one specified, the {#syntax#}std.builtin.default_panic{#endsyntax#}
function from {#syntax#}std/builtin.zig{#endsyntax#}.
</p>
<p>Generally it is better to use {#syntax#}@import("std").debug.panic{#endsyntax#}.
However, {#syntax#}@panic{#endsyntax#} can be useful for 2 scenarios:
</p>
<ul>
<li>From library code, calling the programmer's panic function if they exposed one in the root source file.</li>
<li>When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.</li>
</ul>
{#see_also|Root Source File#}
{#header_close#}
{#header_open|@popCount#}
<pre>{#syntax#}@popCount(operand: anytype){#endsyntax#}</pre>
<p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type.</p>
<p>{#syntax#}operand{#endsyntax#} may be an {#link|integer|Integers#} or {#link|vector|Vectors#}.</p>
<p>Counts the number of bits set in an integer.</p>
<p>
If {#syntax#}operand{#endsyntax#} is a {#link|comptime#}-known integer,
the return type is {#syntax#}comptime_int{#endsyntax#}.
Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number
of bits that can represent the bit count of the integer type.
</p>
{#see_also|@ctz|@clz#}
{#header_close#}
{#header_open|@prefetch#}
<pre>{#syntax#}@prefetch(ptr: anytype, comptime options: std.builtin.PrefetchOptions){#endsyntax#}</pre>
<p>
This builtin tells the compiler to emit a prefetch instruction if supported by the
target CPU. If the target CPU does not support the requested prefetch instruction,
this builtin is a no-op. This function has no effect on the behavior of the program,
only on the performance characteristics.
</p>
<p>
The {#syntax#}ptr{#endsyntax#} argument may be any pointer type and determines the memory
address to prefetch. This function does not dereference the pointer, it is perfectly legal
to pass a pointer to invalid memory to this function and no illegal behavior will result.
</p>
<p>
The {#syntax#}options{#endsyntax#} argument is the following struct:
</p>
{#code_begin|syntax|builtin#}
/// This data structure is used by the Zig language code generation and
/// therefore must be kept in sync with the compiler implementation.
pub const PrefetchOptions = struct {
/// Whether the prefetch should prepare for a read or a write.
rw: Rw = .read,
/// 0 means no temporal locality. That is, the data can be immediately
/// dropped from the cache after it is accessed.
///
/// 3 means high temporal locality. That is, the data should be kept in
/// the cache as it is likely to be accessed again soon.
locality: u2 = 3,
/// The cache that the prefetch should be preformed on.
cache: Cache = .data,
pub const Rw = enum {
read,
write,
};
pub const Cache = enum {
instruction,
data,
};
};
{#code_end#}
{#header_close#}
{#header_open|@ptrCast#}
<pre>{#syntax#}@ptrCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}</pre>
<p>
Converts a pointer of one type to a pointer of another type.
</p>
<p>
{#link|Optional Pointers#} are allowed. Casting an optional pointer which is {#link|null#}
to a non-optional pointer invokes safety-checked {#link|Undefined Behavior#}.
</p>
<p>
{#syntax#}@ptrCast{#endsyntax#} cannot be used for:
</p>
<ul>
<li>Removing {#syntax#}const{#endsyntax#} or {#syntax#}volatile{#endsyntax#} qualifier. TODO add a {#syntax#}@qualCast{#endsyntax#} builtin.</li>
<li>Changing pointer address space, use {#link|@addrSpaceCast#}</li>
<li>Increasing pointer alignment, use {#link|@alignCast#}</li>
<li>Casting a non-slice pointer to a slice, use slicing syntax {#syntax#}ptr[start..end]{#endsyntax#}</li>
</ul>
{#header_close#}
{#header_open|@ptrToInt#}
<pre>{#syntax#}@ptrToInt(value: anytype) usize{#endsyntax#}</pre>
<p>
Converts {#syntax#}value{#endsyntax#} to a {#syntax#}usize{#endsyntax#} which is the address of the pointer.
{#syntax#}value{#endsyntax#} can be {#syntax#}*T{#endsyntax#} or {#syntax#}?*T{#endsyntax#}.
</p>
<p>To convert the other way, use {#link|@intToPtr#}</p>
{#header_close#}
{#header_open|@rem#}
<pre>{#syntax#}@rem(numerator: T, denominator: T) T{#endsyntax#}</pre>
<p>
Remainder division. For unsigned integers this is the same as
{#syntax#}numerator % denominator{#endsyntax#}. Caller guarantees {#syntax#}denominator > 0{#endsyntax#}, otherwise the
operation will result in a {#link|Remainder Division by Zero#} when runtime safety checks are enabled.
</p>
<ul>
<li>{#syntax#}@rem(-5, 3) == -2{#endsyntax#}</li>
<li>{#syntax#}(@divTrunc(a, b) * b) + @rem(a, b) == a{#endsyntax#}</li>
</ul>
<p>For a function that returns an error code, see {#syntax#}@import("std").math.rem{#endsyntax#}.</p>
{#see_also|@mod#}
{#header_close#}
{#header_open|@returnAddress#}
<pre>{#syntax#}@returnAddress() usize{#endsyntax#}</pre>
<p>
This function returns the address of the next machine code instruction that will be executed
when the current function returns.
</p>
<p>
The implications of this are target-specific and not consistent across
all platforms.
</p>
<p>
This function is only valid within function scope. If the function gets inlined into
a calling function, the returned address will apply to the calling function.
</p>
{#header_close#}
{#header_open|@select#}
<pre>{#syntax#}@select(comptime T: type, pred: @Vector(len, bool), a: @Vector(len, T), b: @Vector(len, T)) @Vector(len, T){#endsyntax#}</pre>
<p>
Selects values element-wise from {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} based on {#syntax#}pred{#endsyntax#}. If {#syntax#}pred[i]{#endsyntax#} is {#syntax#}true{#endsyntax#}, the corresponding element in the result will be {#syntax#}a[i]{#endsyntax#} and otherwise {#syntax#}b[i]{#endsyntax#}.
</p>
{#see_also|Vectors#}
{#header_close#}
{#header_open|@setAlignStack#}
<pre>{#syntax#}@setAlignStack(comptime alignment: u29){#endsyntax#}</pre>
<p>
Ensures that a function will have a stack alignment of at least {#syntax#}alignment{#endsyntax#} bytes.
</p>
{#header_close#}
{#header_open|@setCold#}
<pre>{#syntax#}@setCold(comptime is_cold: bool){#endsyntax#}</pre>
<p>
Tells the optimizer that a function is rarely called.
</p>
{#header_close#}
{#header_open|@setEvalBranchQuota#}
<pre>{#syntax#}@setEvalBranchQuota(comptime new_quota: u32){#endsyntax#}</pre>
<p>
Changes the maximum number of backwards branches that compile-time code
execution can use before giving up and making a compile error.
</p>
<p>
If the {#syntax#}new_quota{#endsyntax#} is smaller than the default quota ({#syntax#}1000{#endsyntax#}) or
a previously explicitly set quota, it is ignored.
</p>
<p>
Example:
</p>
{#code_begin|test_err|test_without_setEvalBranchQuota_builtin|evaluation exceeded 1000 backwards branches#}
test "foo" {
comptime {
var i = 0;
while (i < 1001) : (i += 1) {}
}
}
{#code_end#}
<p>Now we use {#syntax#}@setEvalBranchQuota{#endsyntax#}:</p>
{#code_begin|test|test_setEvalBranchQuota_builtin#}
test "foo" {
comptime {
@setEvalBranchQuota(1001);
var i = 0;
while (i < 1001) : (i += 1) {}
}
}
{#code_end#}
{#see_also|comptime#}
{#header_close#}
{#header_open|@setFloatMode#}
<pre>{#syntax#}@setFloatMode(comptime mode: @import("std").builtin.FloatMode){#endsyntax#}</pre>
<p>
Sets the floating point mode of the current scope. Possible values are:
</p>
{#code_begin|syntax|FloatMode#}
pub const FloatMode = enum {
Strict,
Optimized,
};
{#code_end#}
<ul>
<li>
{#syntax#}Strict{#endsyntax#} (default) - Floating point operations follow strict IEEE compliance.
</li>
<li>
{#syntax#}Optimized{#endsyntax#} - Floating point operations may do all of the following:
<ul>
<li>Assume the arguments and result are not NaN. Optimizations are required to retain defined behavior over NaNs, but the value of the result is undefined.</li>
<li>Assume the arguments and result are not +/-Inf. Optimizations are required to retain defined behavior over +/-Inf, but the value of the result is undefined.</li>
<li>Treat the sign of a zero argument or result as insignificant.</li>
<li>Use the reciprocal of an argument rather than perform division.</li>
<li>Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-add).</li>
<li>Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate).</li>
</ul>
This is equivalent to <code>-ffast-math</code> in GCC.
</li>
</ul>
<p>
The floating point mode is inherited by child scopes, and can be overridden in any scope.
You can set the floating point mode in a struct or module scope by using a comptime block.
</p>
{#see_also|Floating Point Operations#}
{#header_close#}
{#header_open|@setRuntimeSafety#}
<pre>{#syntax#}@setRuntimeSafety(comptime safety_on: bool) void{#endsyntax#}</pre>
<p>
Sets whether runtime safety checks are enabled for the scope that contains the function call.
</p>
{#code_begin|test_safety|test_setRuntimeSafety_builtin|integer overflow#}
{#code_release_fast#}
test "@setRuntimeSafety" {
// The builtin applies to the scope that it is called in. So here, integer overflow
// will not be caught in ReleaseFast and ReleaseSmall modes:
// var x: u8 = 255;
// x += 1; // undefined behavior in ReleaseFast/ReleaseSmall modes.
{
// However this block has safety enabled, so safety checks happen here,
// even in ReleaseFast and ReleaseSmall modes.
@setRuntimeSafety(true);
var x: u8 = 255;
x += 1;
{
// The value can be overridden at any scope. So here integer overflow
// would not be caught in any build mode.
@setRuntimeSafety(false);
// var x: u8 = 255;
// x += 1; // undefined behavior in all build modes.
}
}
}
{#code_end#}
<p>Note: it is <a href="https://github.com/ziglang/zig/issues/978">planned</a> to replace
{#syntax#}@setRuntimeSafety{#endsyntax#} with <code>@optimizeFor</code></p>
{#header_close#}
{#header_open|@shlExact#}
<pre>{#syntax#}@shlExact(value: T, shift_amt: Log2T) T{#endsyntax#}</pre>
<p>
Performs the left shift operation ({#syntax#}<<{#endsyntax#}).
For unsigned integers, the result is {#link|undefined#} if any 1 bits
are shifted out. For signed integers, the result is {#link|undefined#} if
any bits that disagree with the resultant sign bit are shifted out.
</p>
<p>
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(T).Int.bits){#endsyntax#} bits.
This is because {#syntax#}shift_amt >= @typeInfo(T).Int.bits{#endsyntax#} is undefined behavior.
</p>
{#see_also|@shrExact|@shlWithOverflow#}
{#header_close#}
{#header_open|@shlWithOverflow#}
<pre>{#syntax#}@shlWithOverflow(a: anytype, shift_amt: Log2T) struct { @TypeOf(a), u1 }{#endsyntax#}</pre>
<p>
Performs {#syntax#}a << b{#endsyntax#} and returns a tuple with the result and a possible overflow bit.
</p>
<p>
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(@TypeOf(a)).Int.bits){#endsyntax#} bits.
This is because {#syntax#}shift_amt >= @typeInfo(@TypeOf(a)).Int.bits{#endsyntax#} is undefined behavior.
</p>
{#see_also|@shlExact|@shrExact#}
{#header_close#}
{#header_open|@shrExact#}
<pre>{#syntax#}@shrExact(value: T, shift_amt: Log2T) T{#endsyntax#}</pre>
<p>
Performs the right shift operation ({#syntax#}>>{#endsyntax#}). Caller guarantees
that the shift will not shift any 1 bits out.
</p>
<p>
The type of {#syntax#}shift_amt{#endsyntax#} is an unsigned integer with {#syntax#}log2(@typeInfo(T).Int.bits){#endsyntax#} bits.
This is because {#syntax#}shift_amt >= @typeInfo(T).Int.bits{#endsyntax#} is undefined behavior.
</p>
{#see_also|@shlExact|@shlWithOverflow#}
{#header_close#}
{#header_open|@shuffle#}
<pre>{#syntax#}@shuffle(comptime E: type, a: @Vector(a_len, E), b: @Vector(b_len, E), comptime mask: @Vector(mask_len, i32)) @Vector(mask_len, E){#endsyntax#}</pre>
<p>
Constructs a new {#link|vector|Vectors#} by selecting elements from {#syntax#}a{#endsyntax#} and
{#syntax#}b{#endsyntax#} based on {#syntax#}mask{#endsyntax#}.
</p>
<p>
Each element in {#syntax#}mask{#endsyntax#} selects an element from either {#syntax#}a{#endsyntax#} or
{#syntax#}b{#endsyntax#}. Positive numbers select from {#syntax#}a{#endsyntax#} starting at 0.
Negative values select from {#syntax#}b{#endsyntax#}, starting at {#syntax#}-1{#endsyntax#} and going down.
It is recommended to use the {#syntax#}~{#endsyntax#} operator for indexes from {#syntax#}b{#endsyntax#}
so that both indexes can start from {#syntax#}0{#endsyntax#} (i.e. {#syntax#}~@as(i32, 0){#endsyntax#} is
{#syntax#}-1{#endsyntax#}).
</p>
<p>
For each element of {#syntax#}mask{#endsyntax#}, if it or the selected value from
{#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#},
then the resulting element is {#syntax#}undefined{#endsyntax#}.
</p>
<p>
{#syntax#}a_len{#endsyntax#} and {#syntax#}b_len{#endsyntax#} may differ in length. Out-of-bounds element
indexes in {#syntax#}mask{#endsyntax#} result in compile errors.
</p>
<p>
If {#syntax#}a{#endsyntax#} or {#syntax#}b{#endsyntax#} is {#syntax#}undefined{#endsyntax#}, it
is equivalent to a vector of all {#syntax#}undefined{#endsyntax#} with the same length as the other vector.
If both vectors are {#syntax#}undefined{#endsyntax#}, {#syntax#}@shuffle{#endsyntax#} returns
a vector with all elements {#syntax#}undefined{#endsyntax#}.
</p>
<p>
{#syntax#}E{#endsyntax#} must be an {#link|integer|Integers#}, {#link|float|Floats#},
{#link|pointer|Pointers#}, or {#syntax#}bool{#endsyntax#}. The mask may be any vector length, and its
length determines the result length.
</p>
{#code_begin|test|test_shuffle_builtin#}
const std = @import("std");
const expect = std.testing.expect;
test "vector @shuffle" {
const a = @Vector(7, u8){ 'o', 'l', 'h', 'e', 'r', 'z', 'w' };
const b = @Vector(4, u8){ 'w', 'd', '!', 'x' };
// To shuffle within a single vector, pass undefined as the second argument.
// Notice that we can re-order, duplicate, or omit elements of the input vector
const mask1 = @Vector(5, i32){ 2, 3, 1, 1, 0 };
const res1: @Vector(5, u8) = @shuffle(u8, a, undefined, mask1);
try expect(std.mem.eql(u8, &@as([5]u8, res1), "hello"));
// Combining two vectors
const mask2 = @Vector(6, i32){ -1, 0, 4, 1, -2, -3 };
const res2: @Vector(6, u8) = @shuffle(u8, a, b, mask2);
try expect(std.mem.eql(u8, &@as([6]u8, res2), "world!"));
}
{#code_end#}
{#see_also|Vectors#}
{#header_close#}
{#header_open|@sizeOf#}
<pre>{#syntax#}@sizeOf(comptime T: type) comptime_int{#endsyntax#}</pre>
<p>
This function returns the number of bytes it takes to store {#syntax#}T{#endsyntax#} in memory.
The result is a target-specific compile time constant.
</p>
<p>
This size may contain padding bytes. If there were two consecutive T in memory, this would be the offset
in bytes between element at index 0 and the element at index 1. For {#link|integer|Integers#},
consider whether you want to use {#syntax#}@sizeOf(T){#endsyntax#} or
{#syntax#}@typeInfo(T).Int.bits{#endsyntax#}.
</p>
<p>
This function measures the size at runtime. For types that are disallowed at runtime, such as
{#syntax#}comptime_int{#endsyntax#} and {#syntax#}type{#endsyntax#}, the result is {#syntax#}0{#endsyntax#}.
</p>
{#see_also|@bitSizeOf|@typeInfo#}
{#header_close#}
{#header_open|@splat#}
<pre>{#syntax#}@splat(comptime len: u32, scalar: anytype) @Vector(len, @TypeOf(scalar)){#endsyntax#}</pre>
<p>
Produces a vector of length {#syntax#}len{#endsyntax#} where each element is the value
{#syntax#}scalar{#endsyntax#}:
</p>
{#code_begin|test|test_splat_builtin#}
const std = @import("std");
const expect = std.testing.expect;
test "vector @splat" {
const scalar: u32 = 5;
const result = @splat(4, scalar);
comptime try expect(@TypeOf(result) == @Vector(4, u32));
try expect(std.mem.eql(u32, &@as([4]u32, result), &[_]u32{ 5, 5, 5, 5 }));
}
{#code_end#}
<p>
{#syntax#}scalar{#endsyntax#} must be an {#link|integer|Integers#}, {#link|bool|Primitive Types#},
{#link|float|Floats#}, or {#link|pointer|Pointers#}.
</p>
{#see_also|Vectors|@shuffle#}
{#header_close#}
{#header_open|@reduce#}
<pre>{#syntax#}@reduce(comptime op: std.builtin.ReduceOp, value: anytype) E{#endsyntax#}</pre>
<p>
Transforms a {#link|vector|Vectors#} into a scalar value (of type <code>E</code>)
by performing a sequential horizontal reduction of its elements using the
specified operator {#syntax#}op{#endsyntax#}.
</p>
<p>
Not every operator is available for every vector element type:
</p>
<ul>
<li>Every operator is available for {#link|integer|Integers#} vectors.</li>
<li>{#syntax#}.And{#endsyntax#}, {#syntax#}.Or{#endsyntax#},
{#syntax#}.Xor{#endsyntax#} are additionally available for
{#syntax#}bool{#endsyntax#} vectors,</li>
<li>{#syntax#}.Min{#endsyntax#}, {#syntax#}.Max{#endsyntax#},
{#syntax#}.Add{#endsyntax#}, {#syntax#}.Mul{#endsyntax#} are
additionally available for {#link|floating point|Floats#} vectors,</li>
</ul>
<p>
Note that {#syntax#}.Add{#endsyntax#} and {#syntax#}.Mul{#endsyntax#}
reductions on integral types are wrapping; when applied on floating point
types the operation associativity is preserved, unless the float mode is
set to {#syntax#}Optimized{#endsyntax#}.
</p>
{#code_begin|test|test_reduce_builtin#}
const std = @import("std");
const expect = std.testing.expect;
test "vector @reduce" {
const value = @Vector(4, i32){ 1, -1, 1, -1 };
const result = value > @splat(4, @as(i32, 0));
// result is { true, false, true, false };
comptime try expect(@TypeOf(result) == @Vector(4, bool));
const is_all_true = @reduce(.And, result);
comptime try expect(@TypeOf(is_all_true) == bool);
try expect(is_all_true == false);
}
{#code_end#}
{#see_also|Vectors|@setFloatMode#}
{#header_close#}
{#header_open|@src#}
<pre>{#syntax#}@src() std.builtin.SourceLocation{#endsyntax#}</pre>
<p>
Returns a {#syntax#}SourceLocation{#endsyntax#} struct representing the function's name and location in the source code. This must be called in a function.
</p>
{#code_begin|test|test_src_builtin#}
const std = @import("std");
const expect = std.testing.expect;
test "@src" {
try doTheTest();
}
fn doTheTest() !void {
const src = @src();
try expect(src.line == 9);
try expect(src.column == 17);
try expect(std.mem.endsWith(u8, src.fn_name, "doTheTest"));
try expect(std.mem.endsWith(u8, src.file, "test_src_builtin.zig"));
}
{#code_end#}
{#header_close#}
{#header_open|@sqrt#}
<pre>{#syntax#}@sqrt(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Performs the square root of a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@sin#}
<pre>{#syntax#}@sin(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Sine trigonometric function on a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@cos#}
<pre>{#syntax#}@cos(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Cosine trigonometric function on a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@tan#}
<pre>{#syntax#}@tan(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Tangent trigonometric function on a floating point number.
Uses a dedicated hardware instruction when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@exp#}
<pre>{#syntax#}@exp(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Base-e exponential function on a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@exp2#}
<pre>{#syntax#}@exp2(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@log#}
<pre>{#syntax#}@log(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@log2#}
<pre>{#syntax#}@log2(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@log10#}
<pre>{#syntax#}@log10(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@fabs#}
<pre>{#syntax#}@fabs(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Returns the absolute value of a floating point number. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@floor#}
<pre>{#syntax#}@floor(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Returns the largest integral value not greater than the given floating point number.
Uses a dedicated hardware instruction when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@ceil#}
<pre>{#syntax#}@ceil(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Returns the smallest integral value not less than the given floating point number.
Uses a dedicated hardware instruction when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@trunc#}
<pre>{#syntax#}@trunc(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Rounds the given floating point number to an integer, towards zero.
Uses a dedicated hardware instruction when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@round#}
<pre>{#syntax#}@round(value: anytype) @TypeOf(value){#endsyntax#}</pre>
<p>
Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction
when available.
</p>
<p>
Supports {#link|Floats#} and {#link|Vectors#} of floats, with the caveat that
<a href="https://github.com/ziglang/zig/issues/4026">some float operations are not yet implemented for all float types</a>.
</p>
{#header_close#}
{#header_open|@subWithOverflow#}
<pre>{#syntax#}@subWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 }{#endsyntax#}</pre>
<p>
Performs {#syntax#}a - b{#endsyntax#} and returns a tuple with the result and a possible overflow bit.
</p>
{#header_close#}
{#header_open|@tagName#}
<pre>{#syntax#}@tagName(value: anytype) [:0]const u8{#endsyntax#}</pre>
<p>
Converts an enum value or union value to a string literal representing the name.</p><p>If the enum is non-exhaustive and the tag value does not map to a name, it invokes safety-checked {#link|Undefined Behavior#}.
</p>
{#header_close#}
{#header_open|@This#}
<pre>{#syntax#}@This() type{#endsyntax#}</pre>
<p>
Returns the innermost struct, enum, or union that this function call is inside.
This can be useful for an anonymous struct that needs to refer to itself:
</p>
{#code_begin|test|test_this_builtin#}
const std = @import("std");
const expect = std.testing.expect;
test "@This()" {
var items = [_]i32{ 1, 2, 3, 4 };
const list = List(i32){ .items = items[0..] };
try expect(list.length() == 4);
}
fn List(comptime T: type) type {
return struct {
const Self = @This();
items: []T,
fn length(self: Self) usize {
return self.items.len;
}
};
}
{#code_end#}
<p>
When {#syntax#}@This(){#endsyntax#} is used at file scope, it returns a reference to the
struct that corresponds to the current file.
</p>
{#header_close#}
{#header_open|@truncate#}
<pre>{#syntax#}@truncate(comptime T: type, integer: anytype) T{#endsyntax#}</pre>
<p>
This function truncates bits from an integer type, resulting in a smaller
or same-sized integer type.
</p>
<p>
This function always truncates the significant bits of the integer, regardless
of endianness on the target platform.
</p>
<p>
Calling {#syntax#}@truncate{#endsyntax#} on a number out of range of the destination type is well defined and working code:
</p>
{#code_begin|test|test_truncate_builtin#}
const std = @import("std");
const expect = std.testing.expect;
test "integer truncation" {
var a: u16 = 0xabcd;
var b: u8 = @truncate(u8, a);
try expect(b == 0xcd);
}
{#code_end#}
<p>
Use {#link|@intCast#} to convert numbers guaranteed to fit the destination type.
</p>
{#header_close#}
{#header_open|@Type#}
<pre>{#syntax#}@Type(comptime info: std.builtin.Type) type{#endsyntax#}</pre>
<p>
This function is the inverse of {#link|@typeInfo#}. It reifies type information
into a {#syntax#}type{#endsyntax#}.
</p>
<p>
It is available for the following types:
</p>
<ul>
<li>{#syntax#}type{#endsyntax#}</li>
<li>{#syntax#}noreturn{#endsyntax#}</li>
<li>{#syntax#}void{#endsyntax#}</li>
<li>{#syntax#}bool{#endsyntax#}</li>
<li>{#link|Integers#} - The maximum bit count for an integer type is {#syntax#}65535{#endsyntax#}.</li>
<li>{#link|Floats#}</li>
<li>{#link|Pointers#}</li>
<li>{#syntax#}comptime_int{#endsyntax#}</li>
<li>{#syntax#}comptime_float{#endsyntax#}</li>
<li>{#syntax#}@TypeOf(undefined){#endsyntax#}</li>
<li>{#syntax#}@TypeOf(null){#endsyntax#}</li>
<li>{#link|Arrays#}</li>
<li>{#link|Optionals#}</li>
<li>{#link|Error Set Type#}</li>
<li>{#link|Error Union Type#}</li>
<li>{#link|Vectors#}</li>
<li>{#link|opaque#}</li>
<li>{#syntax#}anyframe{#endsyntax#}</li>
<li>{#link|struct#}</li>
<li>{#link|enum#}</li>
<li>{#link|Enum Literals#}</li>
<li>{#link|union#}</li>
<li>{#link|Functions#}</li>
</ul>
{#header_close#}
{#header_open|@typeInfo#}
<pre>{#syntax#}@typeInfo(comptime T: type) std.builtin.Type{#endsyntax#}</pre>
<p>
Provides type reflection.
</p>
<p>
Type information of {#link|structs|struct#}, {#link|unions|union#}, {#link|enums|enum#}, and
{#link|error sets|Error Set Type#} has fields which are guaranteed to be in the same
order as appearance in the source file.
</p>
<p>
Type information of {#link|structs|struct#}, {#link|unions|union#}, {#link|enums|enum#}, and
{#link|opaques|opaque#} has declarations, which are also guaranteed to be in the same
order as appearance in the source file.
</p>
{#header_close#}
{#header_open|@typeName#}
<pre>{#syntax#}@typeName(T: type) *const [N:0]u8{#endsyntax#}</pre>
<p>
This function returns the string representation of a type, as
an array. It is equivalent to a string literal of the type name.
The returned type name is fully qualified with the parent namespace included
as part of the type name with a series of dots.
</p>
{#header_close#}
{#header_open|@TypeOf#}
<pre>{#syntax#}@TypeOf(...) type{#endsyntax#}</pre>
<p>
{#syntax#}@TypeOf{#endsyntax#} is a special builtin function that takes any (nonzero) number of expressions
as parameters and returns the type of the result, using {#link|Peer Type Resolution#}.
</p>
<p>
The expressions are evaluated, however they are guaranteed to have no <em>runtime</em> side-effects:
</p>
{#code_begin|test|test_TypeOf_builtin#}
const std = @import("std");
const expect = std.testing.expect;
test "no runtime side effects" {
var data: i32 = 0;
const T = @TypeOf(foo(i32, &data));
comptime try expect(T == i32);
try expect(data == 0);
}
fn foo(comptime T: type, ptr: *T) T {
ptr.* += 1;
return ptr.*;
}
{#code_end#}
{#header_close#}
{#header_open|@unionInit#}
<pre>{#syntax#}@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union{#endsyntax#}</pre>
<p>
This is the same thing as {#link|union#} initialization syntax, except that the field name is a
{#link|comptime#}-known value rather than an identifier token.
</p>
<p>
{#syntax#}@unionInit{#endsyntax#} forwards its {#link|result location|Result Location Semantics#} to {#syntax#}init_expr{#endsyntax#}.
</p>
{#header_close#}
{#header_open|@Vector#}
<pre>{#syntax#}@Vector(len: comptime_int, Element: type) type{#endsyntax#}</pre>
<p>Creates {#link|Vectors#}.</p>
{#header_close#}
{#header_close#}
{#header_open|Build Mode#}
<p>
Zig has four build modes:
</p>
<ul>
<li>{#link|Debug#} (default)</li>
<li>{#link|ReleaseFast#}</li>
<li>{#link|ReleaseSafe#}</li>
<li>{#link|ReleaseSmall#}</li>
</ul>
<p>
To add standard build options to a <code class="file">build.zig</code> file:
</p>
{#code_begin|syntax|build#}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const exe = b.addExecutable("example", "example.zig");
exe.setBuildMode(b.standardReleaseOptions());
b.default_step.dependOn(&exe.step);
}
{#code_end#}
<p>
This causes these options to be available:
</p>
<dl>
<dt><kbd>-Drelease-safe=[bool]</kbd></dt><dd>Optimizations on and safety on</dd>
<dt><kbd>-Drelease-fast=[bool]</kbd></dt><dd>Optimizations on and safety off</dd>
<dt><kbd>-Drelease-small=[bool]</kbd></dt><dd>Size optimizations on and safety off</dd>
</dl>
{#header_open|Debug#}
{#shell_samp#}$ zig build-exe example.zig{#end_shell_samp#}
<ul>
<li>Fast compilation speed</li>
<li>Safety checks enabled</li>
<li>Slow runtime performance</li>
<li>Large binary size</li>
<li>No reproducible build requirement</li>
</ul>
{#header_close#}
{#header_open|ReleaseFast#}
{#shell_samp#}$ zig build-exe example.zig -O ReleaseFast{#end_shell_samp#}
<ul>
<li>Fast runtime performance</li>
<li>Safety checks disabled</li>
<li>Slow compilation speed</li>
<li>Large binary size</li>
<li>Reproducible build</li>
</ul>
{#header_close#}
{#header_open|ReleaseSafe#}
{#shell_samp#}$ zig build-exe example.zig -O ReleaseSafe{#end_shell_samp#}
<ul>
<li>Medium runtime performance</li>
<li>Safety checks enabled</li>
<li>Slow compilation speed</li>
<li>Large binary size</li>
<li>Reproducible build</li>
</ul>
{#header_close#}
{#header_open|ReleaseSmall#}
{#shell_samp#}$ zig build-exe example.zig -O ReleaseSmall{#end_shell_samp#}
<ul>
<li>Medium runtime performance</li>
<li>Safety checks disabled</li>
<li>Slow compilation speed</li>
<li>Small binary size</li>
<li>Reproducible build</li>
</ul>
{#header_close#}
{#see_also|Compile Variables|Zig Build System|Undefined Behavior#}
{#header_close#}
{#header_open|Single Threaded Builds#}
<p>Zig has a compile option <kbd>--single-threaded</kbd> which has the following effects:</p>
<ul>
<li>All {#link|Thread Local Variables#} are treated as regular {#link|Container Level Variables#}.</li>
<li>The overhead of {#link|Async Functions#} becomes equivalent to function call overhead.</li>
<li>The {#syntax#}@import("builtin").single_threaded{#endsyntax#} becomes {#syntax#}true{#endsyntax#}
and therefore various userland APIs which read this variable become more efficient.
For example {#syntax#}std.Mutex{#endsyntax#} becomes
an empty data structure and all of its functions become no-ops.</li>
</ul>
{#header_close#}
{#header_open|Undefined Behavior#}
<p>
Zig has many instances of undefined behavior. If undefined behavior is
detected at compile-time, Zig emits a compile error and refuses to continue.
Most undefined behavior that cannot be detected at compile-time can be detected
at runtime. In these cases, Zig has safety checks. Safety checks can be disabled
on a per-block basis with {#link|@setRuntimeSafety#}. The {#link|ReleaseFast#}
and {#link|ReleaseSmall#} build modes disable all safety checks (except where overridden
by {#link|@setRuntimeSafety#}) in order to facilitate optimizations.
</p>
<p>
When a safety check fails, Zig crashes with a stack trace, like this:
</p>
{#code_begin|test_err|test_undefined_behavior|reached unreachable code#}
test "safety check" {
unreachable;
}
{#code_end#}
{#header_open|Reaching Unreachable Code#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_reaching_unreachable|reached unreachable code#}
comptime {
assert(false);
}
fn assert(ok: bool) void {
if (!ok) unreachable; // assertion failure
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_reaching_unreachable#}
const std = @import("std");
pub fn main() void {
std.debug.assert(false);
}
{#code_end#}
{#header_close#}
{#header_open|Index out of Bounds#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_index_out_of_bounds|index 5 outside array of length 5#}
comptime {
const array: [5]u8 = "hello".*;
const garbage = array[5];
_ = garbage;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_index_out_of_bounds#}
pub fn main() void {
var x = foo("hello");
_ = x;
}
fn foo(x: []const u8) u8 {
return x[5];
}
{#code_end#}
{#header_close#}
{#header_open|Cast Negative Number to Unsigned Integer#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_invalid_cast|type 'u32' cannot represent integer value '-1'#}
comptime {
var value: i32 = -1;
const unsigned = @intCast(u32, value);
_ = unsigned;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_invalid_cast#}
const std = @import("std");
pub fn main() void {
var value: i32 = -1;
var unsigned = @intCast(u32, value);
std.debug.print("value: {}\n", .{unsigned});
}
{#code_end#}
<p>
To obtain the maximum value of an unsigned integer, use {#syntax#}std.math.maxInt{#endsyntax#}.
</p>
{#header_close#}
{#header_open|Cast Truncates Data#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_invalid_cast_truncate|type 'u8' cannot represent integer value '300'#}
comptime {
const spartan_count: u16 = 300;
const byte = @intCast(u8, spartan_count);
_ = byte;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_invalid_cast_truncate#}
const std = @import("std");
pub fn main() void {
var spartan_count: u16 = 300;
const byte = @intCast(u8, spartan_count);
std.debug.print("value: {}\n", .{byte});
}
{#code_end#}
<p>
To truncate bits, use {#link|@truncate#}.
</p>
{#header_close#}
{#header_open|Integer Overflow#}
{#header_open|Default Operations#}
<p>The following operators can cause integer overflow:</p>
<ul>
<li>{#syntax#}+{#endsyntax#} (addition)</li>
<li>{#syntax#}-{#endsyntax#} (subtraction)</li>
<li>{#syntax#}-{#endsyntax#} (negation)</li>
<li>{#syntax#}*{#endsyntax#} (multiplication)</li>
<li>{#syntax#}/{#endsyntax#} (division)</li>
<li>{#link|@divTrunc#} (division)</li>
<li>{#link|@divFloor#} (division)</li>
<li>{#link|@divExact#} (division)</li>
</ul>
<p>Example with addition at compile-time:</p>
{#code_begin|test_err|test_comptime_overflow|overflow of integer type 'u8' with value '256'#}
comptime {
var byte: u8 = 255;
byte += 1;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_overflow#}
const std = @import("std");
pub fn main() void {
var byte: u8 = 255;
byte += 1;
std.debug.print("value: {}\n", .{byte});
}
{#code_end#}
{#header_close#}
{#header_open|Standard Library Math Functions#}
<p>These functions provided by the standard library return possible errors.</p>
<ul>
<li>{#syntax#}@import("std").math.add{#endsyntax#}</li>
<li>{#syntax#}@import("std").math.sub{#endsyntax#}</li>
<li>{#syntax#}@import("std").math.mul{#endsyntax#}</li>
<li>{#syntax#}@import("std").math.divTrunc{#endsyntax#}</li>
<li>{#syntax#}@import("std").math.divFloor{#endsyntax#}</li>
<li>{#syntax#}@import("std").math.divExact{#endsyntax#}</li>
<li>{#syntax#}@import("std").math.shl{#endsyntax#}</li>
</ul>
<p>Example of catching an overflow for addition:</p>
{#code_begin|exe_err|math_add#}
const math = @import("std").math;
const print = @import("std").debug.print;
pub fn main() !void {
var byte: u8 = 255;
byte = if (math.add(u8, byte, 1)) |result| result else |err| {
print("unable to add one: {s}\n", .{@errorName(err)});
return err;
};
print("result: {}\n", .{byte});
}
{#code_end#}
{#header_close#}
{#header_open|Builtin Overflow Functions#}
<p>
These builtins return a {#syntax#}bool{#endsyntax#} of whether or not overflow
occurred, as well as returning the overflowed bits:
</p>
<ul>
<li>{#link|@addWithOverflow#}</li>
<li>{#link|@subWithOverflow#}</li>
<li>{#link|@mulWithOverflow#}</li>
<li>{#link|@shlWithOverflow#}</li>
</ul>
<p>
Example of {#link|@addWithOverflow#}:
</p>
{#code_begin|exe|addWithOverflow_builtin#}
const print = @import("std").debug.print;
pub fn main() void {
var byte: u8 = 255;
const ov = @addWithOverflow(byte, 10);
if (ov[1] != 0) {
print("overflowed result: {}\n", .{ov[0]});
} else {
print("result: {}\n", .{ov[0]});
}
}
{#code_end#}
{#header_close#}
{#header_open|Wrapping Operations#}
<p>
These operations have guaranteed wraparound semantics.
</p>
<ul>
<li>{#syntax#}+%{#endsyntax#} (wraparound addition)</li>
<li>{#syntax#}-%{#endsyntax#} (wraparound subtraction)</li>
<li>{#syntax#}-%{#endsyntax#} (wraparound negation)</li>
<li>{#syntax#}*%{#endsyntax#} (wraparound multiplication)</li>
</ul>
{#code_begin|test|test_wraparound_semantics#}
const std = @import("std");
const expect = std.testing.expect;
const minInt = std.math.minInt;
const maxInt = std.math.maxInt;
test "wraparound addition and subtraction" {
const x: i32 = maxInt(i32);
const min_val = x +% 1;
try expect(min_val == minInt(i32));
const max_val = min_val -% 1;
try expect(max_val == maxInt(i32));
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Exact Left Shift Overflow#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_shlExact_overwlow|operation caused overflow#}
comptime {
const x = @shlExact(@as(u8, 0b01010101), 2);
_ = x;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_shlExact_overflow#}
const std = @import("std");
pub fn main() void {
var x: u8 = 0b01010101;
var y = @shlExact(x, 2);
std.debug.print("value: {}\n", .{y});
}
{#code_end#}
{#header_close#}
{#header_open|Exact Right Shift Overflow#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_shrExact_overflow|exact shift shifted out 1 bits#}
comptime {
const x = @shrExact(@as(u8, 0b10101010), 2);
_ = x;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_shrExact_overflow#}
const std = @import("std");
pub fn main() void {
var x: u8 = 0b10101010;
var y = @shrExact(x, 2);
std.debug.print("value: {}\n", .{y});
}
{#code_end#}
{#header_close#}
{#header_open|Division by Zero#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_division_by_zero|division by zero#}
comptime {
const a: i32 = 1;
const b: i32 = 0;
const c = a / b;
_ = c;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_division_by_zero#}
const std = @import("std");
pub fn main() void {
var a: u32 = 1;
var b: u32 = 0;
var c = a / b;
std.debug.print("value: {}\n", .{c});
}
{#code_end#}
{#header_close#}
{#header_open|Remainder Division by Zero#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_remainder_division_by_zero|division by zero#}
comptime {
const a: i32 = 10;
const b: i32 = 0;
const c = a % b;
_ = c;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_remainder_division_by_zero#}
const std = @import("std");
pub fn main() void {
var a: u32 = 10;
var b: u32 = 0;
var c = a % b;
std.debug.print("value: {}\n", .{c});
}
{#code_end#}
{#header_close#}
{#header_open|Exact Division Remainder#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_divExact_remainder|exact division produced remainder#}
comptime {
const a: u32 = 10;
const b: u32 = 3;
const c = @divExact(a, b);
_ = c;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_divExact_remainder#}
const std = @import("std");
pub fn main() void {
var a: u32 = 10;
var b: u32 = 3;
var c = @divExact(a, b);
std.debug.print("value: {}\n", .{c});
}
{#code_end#}
{#header_close#}
{#header_open|Attempt to Unwrap Null#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_unwrap_null|unable to unwrap null#}
comptime {
const optional_number: ?i32 = null;
const number = optional_number.?;
_ = number;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_unwrap_null#}
const std = @import("std");
pub fn main() void {
var optional_number: ?i32 = null;
var number = optional_number.?;
std.debug.print("value: {}\n", .{number});
}
{#code_end#}
<p>One way to avoid this crash is to test for null instead of assuming non-null, with
the {#syntax#}if{#endsyntax#} expression:</p>
{#code_begin|exe|testing_null_with_if#}
const print = @import("std").debug.print;
pub fn main() void {
const optional_number: ?i32 = null;
if (optional_number) |number| {
print("got number: {}\n", .{number});
} else {
print("it's null\n", .{});
}
}
{#code_end#}
{#see_also|Optionals#}
{#header_close#}
{#header_open|Attempt to Unwrap Error#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_unwrap_error|caught unexpected error 'UnableToReturnNumber'#}
comptime {
const number = getNumberOrFail() catch unreachable;
_ = number;
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_unwrap_error#}
const std = @import("std");
pub fn main() void {
const number = getNumberOrFail() catch unreachable;
std.debug.print("value: {}\n", .{number});
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}
{#code_end#}
<p>One way to avoid this crash is to test for an error instead of assuming a successful result, with
the {#syntax#}if{#endsyntax#} expression:</p>
{#code_begin|exe|testing_error_with_if#}
const print = @import("std").debug.print;
pub fn main() void {
const result = getNumberOrFail();
if (result) |number| {
print("got number: {}\n", .{number});
} else |err| {
print("got error: {s}\n", .{@errorName(err)});
}
}
fn getNumberOrFail() !i32 {
return error.UnableToReturnNumber;
}
{#code_end#}
{#see_also|Errors#}
{#header_close#}
{#header_open|Invalid Error Code#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_invalid_error_code|integer value '11' represents no error#}
comptime {
const err = error.AnError;
const number = @errorToInt(err) + 10;
const invalid_err = @intToError(number);
_ = invalid_err;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_invalid_error_code#}
const std = @import("std");
pub fn main() void {
var err = error.AnError;
var number = @errorToInt(err) + 500;
var invalid_err = @intToError(number);
std.debug.print("value: {}\n", .{invalid_err});
}
{#code_end#}
{#header_close#}
{#header_open|Invalid Enum Cast#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_invalid_enum_cast|enum 'test_comptime_invalid_enum_cast.Foo' has no tag with value '3'#}
const Foo = enum {
a,
b,
c,
};
comptime {
const a: u2 = 3;
const b = @intToEnum(Foo, a);
_ = b;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_invalid_enum_cast#}
const std = @import("std");
const Foo = enum {
a,
b,
c,
};
pub fn main() void {
var a: u2 = 3;
var b = @intToEnum(Foo, a);
std.debug.print("value: {s}\n", .{@tagName(b)});
}
{#code_end#}
{#header_close#}
{#header_open|Invalid Error Set Cast#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_invalid_error_set_cast|'error.B' not a member of error set 'error{A,C}'#}
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
comptime {
_ = @errSetCast(Set2, Set1.B);
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_invalid_error_set_cast#}
const std = @import("std");
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
pub fn main() void {
foo(Set1.B);
}
fn foo(set1: Set1) void {
const x = @errSetCast(Set2, set1);
std.debug.print("value: {}\n", .{x});
}
{#code_end#}
{#header_close#}
{#header_open|Incorrect Pointer Alignment#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_incorrect_pointer_alignment|pointer address 0x1 is not aligned to 4 bytes#}
comptime {
const ptr = @intToPtr(*align(1) i32, 0x1);
const aligned = @alignCast(4, ptr);
_ = aligned;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_incorrect_pointer_alignment#}
const mem = @import("std").mem;
pub fn main() !void {
var array align(4) = [_]u32{ 0x11111111, 0x11111111 };
const bytes = mem.sliceAsBytes(array[0..]);
if (foo(bytes) != 0x11111111) return error.Wrong;
}
fn foo(bytes: []u8) u32 {
const slice4 = bytes[1..5];
const int_slice = mem.bytesAsSlice(u32, @alignCast(4, slice4));
return int_slice[0];
}
{#code_end#}
{#header_close#}
{#header_open|Wrong Union Field Access#}
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_wrong_union_field_access|access of union field 'float' while field 'int' is active#}
comptime {
var f = Foo{ .int = 42 };
f.float = 12.34;
}
const Foo = union {
float: f32,
int: u32,
};
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_wrong_union_field_access#}
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
bar(&f);
}
fn bar(f: *Foo) void {
f.float = 12.34;
std.debug.print("value: {}\n", .{f.float});
}
{#code_end#}
<p>
This safety is not available for {#syntax#}extern{#endsyntax#} or {#syntax#}packed{#endsyntax#} unions.
</p>
<p>
To change the active field of a union, assign the entire union, like this:
</p>
{#code_begin|exe|change_active_union_field#}
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
bar(&f);
}
fn bar(f: *Foo) void {
f.* = Foo{ .float = 12.34 };
std.debug.print("value: {}\n", .{f.float});
}
{#code_end#}
<p>
To change the active field of a union when a meaningful value for the field is not known,
use {#link|undefined#}, like this:
</p>
{#code_begin|exe|undefined_active_union_field#}
const std = @import("std");
const Foo = union {
float: f32,
int: u32,
};
pub fn main() void {
var f = Foo{ .int = 42 };
f = Foo{ .float = undefined };
bar(&f);
std.debug.print("value: {}\n", .{f.float});
}
fn bar(f: *Foo) void {
f.float = 12.34;
}
{#code_end#}
{#see_also|union|extern union#}
{#header_close#}
{#header_open|Out of Bounds Float to Integer Cast#}
<p>TODO</p>
{#header_close#}
{#header_open|Pointer Cast Invalid Null#}
<p>
This happens when casting a pointer with the address 0 to a pointer which may not have the address 0.
For example, {#link|C Pointers#}, {#link|Optional Pointers#}, and {#link|allowzero#} pointers
allow address zero, but normal {#link|Pointers#} do not.
</p>
<p>At compile-time:</p>
{#code_begin|test_err|test_comptime_invalid_null_pointer_cast|null pointer casted to type#}
comptime {
const opt_ptr: ?*i32 = null;
const ptr = @ptrCast(*i32, opt_ptr);
_ = ptr;
}
{#code_end#}
<p>At runtime:</p>
{#code_begin|exe_err|runtime_invalid_null_pointer_cast#}
pub fn main() void {
var opt_ptr: ?*i32 = null;
var ptr = @ptrCast(*i32, opt_ptr);
_ = ptr;
}
{#code_end#}
{#header_close#}
{#header_close#}
{#header_open|Memory#}
<p>
The Zig language performs no memory management on behalf of the programmer. This is
why Zig has no runtime, and why Zig code works seamlessly in so many environments,
including real-time software, operating system kernels, embedded devices, and
low latency servers. As a consequence, Zig programmers must always be able to answer
the question:
</p>
<p>{#link|Where are the bytes?#}</p>
<p>
Like Zig, the C programming language has manual memory management. However, unlike Zig,
C has a default allocator - <code>malloc</code>, <code>realloc</code>, and <code>free</code>.
When linking against libc, Zig exposes this allocator with {#syntax#}std.heap.c_allocator{#endsyntax#}.
However, by convention, there is no default allocator in Zig. Instead, functions which need to
allocate accept an {#syntax#}Allocator{#endsyntax#} parameter. Likewise, data structures such as
{#syntax#}std.ArrayList{#endsyntax#} accept an {#syntax#}Allocator{#endsyntax#} parameter in
their initialization functions:
</p>
{#code_begin|test|test_allocator#}
const std = @import("std");
const Allocator = std.mem.Allocator;
const expect = std.testing.expect;
test "using an allocator" {
var buffer: [100]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
const allocator = fba.allocator();
const result = try concat(allocator, "foo", "bar");
try expect(std.mem.eql(u8, "foobar", result));
}
fn concat(allocator: Allocator, a: []const u8, b: []const u8) ![]u8 {
const result = try allocator.alloc(u8, a.len + b.len);
std.mem.copy(u8, result, a);
std.mem.copy(u8, result[a.len..], b);
return result;
}
{#code_end#}
<p>
In the above example, 100 bytes of stack memory are used to initialize a
{#syntax#}FixedBufferAllocator{#endsyntax#}, which is then passed to a function.
As a convenience there is a global {#syntax#}FixedBufferAllocator{#endsyntax#}
available for quick tests at {#syntax#}std.testing.allocator{#endsyntax#},
which will also perform basic leak detection.
</p>
<p>
Zig has a general purpose allocator available to be imported
with {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#}. However, it is still recommended to
follow the {#link|Choosing an Allocator#} guide.
</p>
{#header_open|Choosing an Allocator#}
<p>What allocator to use depends on a number of factors. Here is a flow chart to help you decide:
</p>
<ol>
<li>
Are you making a library? In this case, best to accept an {#syntax#}Allocator{#endsyntax#}
as a parameter and allow your library's users to decide what allocator to use.
</li>
<li>Are you linking libc? In this case, {#syntax#}std.heap.c_allocator{#endsyntax#} is likely
the right choice, at least for your main allocator.</li>
<li>
Is the maximum number of bytes that you will need bounded by a number known at
{#link|comptime#}? In this case, use {#syntax#}std.heap.FixedBufferAllocator{#endsyntax#} or
{#syntax#}std.heap.ThreadSafeFixedBufferAllocator{#endsyntax#} depending on whether you need
thread-safety or not.
</li>
<li>
Is your program a command line application which runs from start to end without any fundamental
cyclical pattern (such as a video game main loop, or a web server request handler),
such that it would make sense to free everything at once at the end?
In this case, it is recommended to follow this pattern:
{#code_begin|exe|cli_allocation#}
const std = @import("std");
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const ptr = try allocator.create(i32);
std.debug.print("ptr={*}\n", .{ptr});
}
{#code_end#}
When using this kind of allocator, there is no need to free anything manually. Everything
gets freed at once with the call to {#syntax#}arena.deinit(){#endsyntax#}.
</li>
<li>
Are the allocations part of a cyclical pattern such as a video game main loop, or a web
server request handler? If the allocations can all be freed at once, at the end of the cycle,
for example once the video game frame has been fully rendered, or the web server request has
been served, then {#syntax#}std.heap.ArenaAllocator{#endsyntax#} is a great candidate. As
demonstrated in the previous bullet point, this allows you to free entire arenas at once.
Note also that if an upper bound of memory can be established, then
{#syntax#}std.heap.FixedBufferAllocator{#endsyntax#} can be used as a further optimization.
</li>
<li>
Are you writing a test, and you want to make sure {#syntax#}error.OutOfMemory{#endsyntax#}
is handled correctly? In this case, use {#syntax#}std.testing.FailingAllocator{#endsyntax#}.
</li>
<li>
Are you writing a test? In this case, use {#syntax#}std.testing.allocator{#endsyntax#}.
</li>
<li>
Finally, if none of the above apply, you need a general purpose allocator.
Zig's general purpose allocator is available as a function that takes a {#link|comptime#}
{#link|struct#} of configuration options and returns a type.
Generally, you will set up one {#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#} in
your main function, and then pass it or sub-allocators around to various parts of your
application.
</li>
<li>
You can also consider {#link|Implementing an Allocator#}.
</li>
</ol>
{#header_close#}
{#header_open|Where are the bytes?#}
<p>String literals such as {#syntax#}"foo"{#endsyntax#} are in the global constant data section.
This is why it is an error to pass a string literal to a mutable slice, like this:
</p>
{#code_begin|test_err|test_string_literal_to_slice|expected type '[]u8', found '*const [5:0]u8'#}
fn foo(s: []u8) void {
_ = s;
}
test "string literal to mutable slice" {
foo("hello");
}
{#code_end#}
<p>However if you make the slice constant, then it works:</p>
{#code_begin|test|test_string_literal_to_const_slice#}
fn foo(s: []const u8) void {
_ = s;
}
test "string literal to constant slice" {
foo("hello");
}
{#code_end#}
<p>
Just like string literals, {#syntax#}const{#endsyntax#} declarations, when the value is known at {#link|comptime#},
are stored in the global constant data section. Also {#link|Compile Time Variables#} are stored
in the global constant data section.
</p>
<p>
{#syntax#}var{#endsyntax#} declarations inside functions are stored in the function's stack frame. Once a function returns,
any {#link|Pointers#} to variables in the function's stack frame become invalid references, and
dereferencing them becomes unchecked {#link|Undefined Behavior#}.
</p>
<p>
{#syntax#}var{#endsyntax#} declarations at the top level or in {#link|struct#} declarations are stored in the global
data section.
</p>
<p>
The location of memory allocated with {#syntax#}allocator.alloc{#endsyntax#} or
{#syntax#}allocator.create{#endsyntax#} is determined by the allocator's implementation.
</p>
<p>TODO: thread local variables</p>
{#header_close#}
{#header_open|Implementing an Allocator#}
<p>Zig programmers can implement their own allocators by fulfilling the Allocator interface.
In order to do this one must read carefully the documentation comments in std/mem.zig and
then supply a {#syntax#}allocFn{#endsyntax#} and a {#syntax#}resizeFn{#endsyntax#}.
</p>
<p>
There are many example allocators to look at for inspiration. Look at std/heap.zig and
{#syntax#}std.heap.GeneralPurposeAllocator{#endsyntax#}.
</p>
{#header_close#}
{#header_open|Heap Allocation Failure#}
<p>
Many programming languages choose to handle the possibility of heap allocation failure by
unconditionally crashing. By convention, Zig programmers do not consider this to be a
satisfactory solution. Instead, {#syntax#}error.OutOfMemory{#endsyntax#} represents
heap allocation failure, and Zig libraries return this error code whenever heap allocation
failure prevented an operation from completing successfully.
</p>
<p>
Some have argued that because some operating systems such as Linux have memory overcommit enabled by
default, it is pointless to handle heap allocation failure. There are many problems with this reasoning:
</p>
<ul>
<li>Only some operating systems have an overcommit feature.
<ul>
<li>Linux has it enabled by default, but it is configurable.</li>
<li>Windows does not overcommit.</li>
<li>Embedded systems do not have overcommit.</li>
<li>Hobby operating systems may or may not have overcommit.</li>
</ul>
</li>
<li>
For real-time systems, not only is there no overcommit, but typically the maximum amount
of memory per application is determined ahead of time.
</li>
<li>
When writing a library, one of the main goals is code reuse. By making code handle
allocation failure correctly, a library becomes eligible to be reused in
more contexts.
</li>
<li>
Although some software has grown to depend on overcommit being enabled, its existence
is the source of countless user experience disasters. When a system with overcommit enabled,
such as Linux on default settings, comes close to memory exhaustion, the system locks up
and becomes unusable. At this point, the OOM Killer selects an application to kill
based on heuristics. This non-deterministic decision often results in an important process
being killed, and often fails to return the system back to working order.
</li>
</ul>
{#header_close#}
{#header_open|Recursion#}
<p>
Recursion is a fundamental tool in modeling software. However it has an often-overlooked problem:
unbounded memory allocation.
</p>
<p>
Recursion is an area of active experimentation in Zig and so the documentation here is not final.
You can read a
<a href="https://ziglang.org/download/0.3.0/release-notes.html#recursion">summary of recursion status in the 0.3.0 release notes</a>.
</p>
<p>
The short summary is that currently recursion works normally as you would expect. Although Zig code
is not yet protected from stack overflow, it is planned that a future version of Zig will provide
such protection, with some degree of cooperation from Zig code required.
</p>
{#header_close#}
{#header_open|Lifetime and Ownership#}
<p>
It is the Zig programmer's responsibility to ensure that a {#link|pointer|Pointers#} is not
accessed when the memory pointed to is no longer available. Note that a {#link|slice|Slices#}
is a form of pointer, in that it references other memory.
</p>
<p>
In order to prevent bugs, there are some helpful conventions to follow when dealing with pointers.
In general, when a function returns a pointer, the documentation for the function should explain
who "owns" the pointer. This concept helps the programmer decide when it is appropriate, if ever,
to free the pointer.
</p>
<p>
For example, the function's documentation may say "caller owns the returned memory", in which case
the code that calls the function must have a plan for when to free that memory. Probably in this situation,
the function will accept an {#syntax#}Allocator{#endsyntax#} parameter.
</p>
<p>
Sometimes the lifetime of a pointer may be more complicated. For example, the
{#syntax#}std.ArrayList(T).items{#endsyntax#} slice has a lifetime that remains
valid until the next time the list is resized, such as by appending new elements.
</p>
<p>
The API documentation for functions and data structures should take great care to explain
the ownership and lifetime semantics of pointers. Ownership determines whose responsibility it
is to free the memory referenced by the pointer, and lifetime determines the point at which
the memory becomes inaccessible (lest {#link|Undefined Behavior#} occur).
</p>
{#header_close#}
{#header_close#}
{#header_open|Compile Variables#}
<p>
Compile variables are accessible by importing the {#syntax#}"builtin"{#endsyntax#} package,
which the compiler makes available to every Zig source file. It contains
compile-time constants such as the current target, endianness, and release mode.
</p>
{#code_begin|syntax|compile_variables#}
const builtin = @import("builtin");
const separator = if (builtin.os.tag == .windows) '\\' else '/';
{#code_end#}
<p>
Example of what is imported with {#syntax#}@import("builtin"){#endsyntax#}:
</p>
{#builtin#}
{#see_also|Build Mode#}
{#header_close#}
{#header_open|Root Source File#}
<p>TODO: explain how root source file finds other files</p>
<p>TODO: pub fn main</p>
<p>TODO: pub fn panic</p>
<p>TODO: if linking with libc you can use export fn main</p>
<p>TODO: order independent top level declarations</p>
<p>TODO: lazy analysis</p>
<p>TODO: using comptime { _ = @import() }</p>
{#header_close#}
{#header_open|Zig Build System#}
<p>
The Zig Build System provides a cross-platform, dependency-free way to declare
the logic required to build a project. With this system, the logic to build
a project is written in a build.zig file, using the Zig Build System API to
declare and configure build artifacts and other tasks.
</p>
<p>
Some examples of tasks the build system can help with:
</p>
<ul>
<li>Creating build artifacts by executing the Zig compiler. This includes
building Zig source code as well as C and C++ source code.</li>
<li>Capturing user-configured options and using those options to configure
the build.</li>
<li>Surfacing build configuration as {#link|comptime#} values by providing a
file that can be {#link|imported|@import#} by Zig code.</li>
<li>Caching build artifacts to avoid unnecessarily repeating steps.</li>
<li>Executing build artifacts or system-installed tools.</li>
<li>Running tests and verifying the output of executing a build artifact matches
the expected value.</li>
<li>Running <code>zig fmt</code> on a codebase or a subset of it.</li>
<li>Custom tasks.</li>
</ul>
<p>
To use the build system, run <kbd>zig build --help</kbd>
to see a command-line usage help menu. This will include project-specific
options that were declared in the build.zig script.
</p>
{#header_open|Building an Executable#}
<p>This <code class="file">build.zig</code> file is automatically generated
by <kbd>zig init-exe</kbd>.</p>
{#code_begin|syntax|build_executable#}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("example", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
{#code_end#}
{#header_close#}
{#header_open|Building a Library#}
<p>This <code class="file">build.zig</code> file is automatically generated
by <kbd>zig init-lib</kbd>.</p>
{#code_begin|syntax|build_library#}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const lib = b.addStaticLibrary("example", "src/main.zig");
lib.setBuildMode(mode);
lib.install();
var main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
}
{#code_end#}
{#header_close#}
{#header_open|Compiling C Source Code#}
<pre>{#syntax#}
lib.addCSourceFile("src/lib.c", &[_][]const u8{
"-Wall",
"-Wextra",
"-Werror",
});
{#endsyntax#}</pre>
{#header_close#}
{#header_close#}
{#header_open|C#}
<p>
Although Zig is independent of C, and, unlike most other languages, does not depend on libc,
Zig acknowledges the importance of interacting with existing C code.
</p>
<p>
There are a few ways that Zig facilitates C interop.
</p>
{#header_open|C Type Primitives#}
<p>
These have guaranteed C ABI compatibility and can be used like any other type.
</p>
<ul>
<li>{#syntax#}c_short{#endsyntax#}</li>
<li>{#syntax#}c_ushort{#endsyntax#}</li>
<li>{#syntax#}c_int{#endsyntax#}</li>
<li>{#syntax#}c_uint{#endsyntax#}</li>
<li>{#syntax#}c_long{#endsyntax#}</li>
<li>{#syntax#}c_ulong{#endsyntax#}</li>
<li>{#syntax#}c_longlong{#endsyntax#}</li>
<li>{#syntax#}c_ulonglong{#endsyntax#}</li>
<li>{#syntax#}c_longdouble{#endsyntax#}</li>
</ul>
<p>
To interop with the C {#syntax#}void{#endsyntax#} type, use {#syntax#}anyopaque{#endsyntax#}.
</p>
{#see_also|Primitive Types#}
{#header_close#}
{#header_open|Import from C Header File#}
<p>
The {#syntax#}@cImport{#endsyntax#} builtin function can be used
to directly import symbols from <code class="file">.h</code> files:
</p>
{#code_begin|exe|cImport_builtin#}
{#link_libc#}
const c = @cImport({
// See https://github.com/ziglang/zig/issues/515
@cDefine("_NO_CRT_STDIO_INLINE", "1");
@cInclude("stdio.h");
});
pub fn main() void {
_ = c.printf("hello\n");
}
{#code_end#}
<p>
The {#syntax#}@cImport{#endsyntax#} function takes an expression as a parameter.
This expression is evaluated at compile-time and is used to control
preprocessor directives and include multiple <code class="file">.h</code> files:
</p>
{#syntax_block|zig|@cImport Expression#}
const builtin = @import("builtin");
const c = @cImport({
@cDefine("NDEBUG", builtin.mode == .ReleaseFast);
if (something) {
@cDefine("_GNU_SOURCE", {});
}
@cInclude("stdlib.h");
if (something) {
@cUndef("_GNU_SOURCE");
}
@cInclude("soundio.h");
});
{#end_syntax_block#}
{#see_also|@cImport|@cInclude|@cDefine|@cUndef|@import#}
{#header_close#}
{#header_open|C Translation CLI#}
<p>
Zig's C translation capability is available as a CLI tool via <kbd>zig translate-c</kbd>.
It requires a single filename as an argument. It may also take a set of optional flags that are
forwarded to clang. It writes the translated file to stdout.
</p>
{#header_open|Command line flags#}
<ul>
<li>
<kbd>-I</kbd>:
Specify a search directory for include files. May be used multiple times. Equivalent to
<a href="https://releases.llvm.org/12.0.0/tools/clang/docs/ClangCommandLineReference.html#cmdoption-clang-i-dir">
clang's <kbd>-I</kbd> flag</a>. The current directory is <em>not</em> included by default;
use <kbd>-I.</kbd> to include it.
</li>
<li>
<kbd>-D</kbd>: Define a preprocessor macro. Equivalent to
<a href="https://releases.llvm.org/12.0.0/tools/clang/docs/ClangCommandLineReference.html#cmdoption-clang-d-macro">
clang's <kbd>-D</kbd> flag</a>.
</li>
<li>
<kbd>-cflags [flags] --</kbd>: Pass arbitrary additional
<a href="https://releases.llvm.org/12.0.0/tools/clang/docs/ClangCommandLineReference.html">command line
flags</a> to clang. Note: the list of flags must end with <kbd>--</kbd>
</li>
<li>
<kbd>-target</kbd>: The {#link|target triple|Targets#} for the translated Zig code.
If no target is specified, the current host target will be used.
</li>
</ul>
{#header_close#}
{#header_open|Using -target and -cflags#}
<p>
<strong>Important!</strong> When translating C code with <kbd>zig translate-c</kbd>,
you <strong>must</strong> use the same <kbd>-target</kbd> triple that you will use when compiling
the translated code. In addition, you <strong>must</strong> ensure that the <kbd>-cflags</kbd> used,
if any, match the cflags used by code on the target system. Using the incorrect <kbd>-target</kbd>
or <kbd>-cflags</kbd> could result in clang or Zig parse failures, or subtle ABI incompatibilities
when linking with C code.
</p>
{#syntax_block|c|varytarget.h#}
long FOO = __LONG_MAX__;
{#end_syntax_block#}
{#shell_samp#}$ zig translate-c -target thumb-freestanding-gnueabihf varytarget.h|grep FOO
pub export var FOO: c_long = 2147483647;
$ zig translate-c -target x86_64-macos-gnu varytarget.h|grep FOO
pub export var FOO: c_long = 9223372036854775807;{#end_shell_samp#}
{#syntax_block|c|varycflags.h#}
enum FOO { BAR };
int do_something(enum FOO foo);
{#end_syntax_block#}
{#shell_samp#}$ zig translate-c varycflags.h|grep -B1 do_something
pub const enum_FOO = c_uint;
pub extern fn do_something(foo: enum_FOO) c_int;
$ zig translate-c -cflags -fshort-enums -- varycflags.h|grep -B1 do_something
pub const enum_FOO = u8;
pub extern fn do_something(foo: enum_FOO) c_int;{#end_shell_samp#}
{#header_close#}
{#header_open|@cImport vs translate-c#}
<p>{#syntax#}@cImport{#endsyntax#} and <kbd>zig translate-c</kbd> use the same underlying
C translation functionality, so on a technical level they are equivalent. In practice,
{#syntax#}@cImport{#endsyntax#} is useful as a way to quickly and easily access numeric constants, typedefs,
and record types without needing any extra setup. If you need to pass {#link|cflags|Using -target and -cflags#}
to clang, or if you would like to edit the translated code, it is recommended to use
<kbd>zig translate-c</kbd> and save the results to a file. Common reasons for editing
the generated code include: changing {#syntax#}anytype{#endsyntax#} parameters in function-like macros to more
specific types; changing {#syntax#}[*c]T{#endsyntax#} pointers to {#syntax#}[*]T{#endsyntax#} or
{#syntax#}*T{#endsyntax#} pointers for improved type safety; and
{#link|enabling or disabling runtime safety|@setRuntimeSafety#} within specific functions.
</p>
{#header_close#}
{#see_also|Targets|C Type Primitives|Pointers|C Pointers|Import from C Header File|@cInclude|@cImport|@setRuntimeSafety#}
{#header_close#}
{#header_open|C Translation Caching#}
<p>
The C translation feature (whether used via <kbd>zig translate-c</kbd> or
{#syntax#}@cImport{#endsyntax#}) integrates with the Zig caching system. Subsequent runs with
the same source file, target, and cflags will use the cache instead of repeatedly translating
the same code.
</p>
<p>
To see where the cached files are stored when compiling code that uses {#syntax#}@cImport{#endsyntax#},
use the <kbd>--verbose-cimport</kbd> flag:
</p>
{#code_begin|exe|verbose_cimport_flag#}
{#link_libc#}
{#code_verbose_cimport#}
const c = @cImport({
@cDefine("_NO_CRT_STDIO_INLINE", "1");
@cInclude("stdio.h");
});
pub fn main() void {
_ = c;
}
{#code_end#}
<p>
<code class="file">cimport.h</code> contains the file to translate (constructed from calls to
{#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#}),
<code class="file">cimport.h.d</code> is the list of file dependencies, and
<code class="file">cimport.zig</code> contains the translated output.
</p>
{#see_also|Import from C Header File|C Translation CLI|@cInclude|@cImport#}
{#header_close#}
{#header_open|Translation failures#}
<p>
Some C constructs cannot be translated to Zig - for example, <em>goto</em>,
structs with bitfields, and token-pasting macros. Zig employs <em>demotion</em> to allow translation
to continue in the face of non-translatable entities.
</p>
<p>
Demotion comes in three varieties - {#link|opaque#}, <em>extern</em>, and
{#syntax#}@compileError{#endsyntax#}.
C structs and unions that cannot be translated correctly will be translated as {#syntax#}opaque{}{#endsyntax#}.
Functions that contain opaque types or code constructs that cannot be translated will be demoted
to {#syntax#}extern{#endsyntax#} declarations.
Thus, non-translatable types can still be used as pointers, and non-translatable functions
can be called so long as the linker is aware of the compiled function.
</p>
<p>
{#syntax#}@compileError{#endsyntax#} is used when top-level definitions (global variables,
function prototypes, macros) cannot be translated or demoted. Since Zig uses lazy analysis for
top-level declarations, untranslatable entities will not cause a compile error in your code unless
you actually use them.
</p>
{#see_also|opaque|extern|@compileError#}
{#header_close#}
{#header_open|C Macros#}
<p>
C Translation makes a best-effort attempt to translate function-like macros into equivalent
Zig functions. Since C macros operate at the level of lexical tokens, not all C macros
can be translated to Zig. Macros that cannot be translated will be demoted to
{#syntax#}@compileError{#endsyntax#}. Note that C code which <em>uses</em> macros will be
translated without any additional issues (since Zig operates on the pre-processed source
with macros expanded). It is merely the macros themselves which may not be translatable to
Zig.
</p>
<p>Consider the following example:</p>
{#syntax_block|c|macro.c#}
#define MAKELOCAL(NAME, INIT) int NAME = INIT
int foo(void) {
MAKELOCAL(a, 1);
MAKELOCAL(b, 2);
return a + b;
}
{#end_syntax_block#}
{#shell_samp#}$ zig translate-c macro.c > macro.zig{#end_shell_samp#}
{#code_begin|syntax|macro#}
pub export fn foo() c_int {
var a: c_int = 1;
var b: c_int = 2;
return a + b;
}
pub const MAKELOCAL = @compileError("unable to translate C expr: unexpected token .Equal"); // macro.c:1:9
{#code_end#}
<p>Note that {#syntax#}foo{#endsyntax#} was translated correctly despite using a non-translatable
macro. {#syntax#}MAKELOCAL{#endsyntax#} was demoted to {#syntax#}@compileError{#endsyntax#} since
it cannot be expressed as a Zig function; this simply means that you cannot directly use
{#syntax#}MAKELOCAL{#endsyntax#} from Zig.
</p>
{#see_also|@compileError#}
{#header_close#}
{#header_open|C Pointers#}
<p>
This type is to be avoided whenever possible. The only valid reason for using a C pointer is in
auto-generated code from translating C code.
</p>
<p>
When importing C header files, it is ambiguous whether pointers should be translated as
single-item pointers ({#syntax#}*T{#endsyntax#}) or many-item pointers ({#syntax#}[*]T{#endsyntax#}).
C pointers are a compromise so that Zig code can utilize translated header files directly.
</p>
<p>{#syntax#}[*c]T{#endsyntax#} - C pointer.</p>
<ul>
<li>Supports all the syntax of the other two pointer types.</li>
<li>Coerces to other pointer types, as well as {#link|Optional Pointers#}.
When a C pointer is coerced to a non-optional pointer, safety-checked
{#link|Undefined Behavior#} occurs if the address is 0.
</li>
<li>Allows address 0. On non-freestanding targets, dereferencing address 0 is safety-checked
{#link|Undefined Behavior#}. Optional C pointers introduce another bit to keep track of
null, just like {#syntax#}?usize{#endsyntax#}. Note that creating an optional C pointer
is unnecessary as one can use normal {#link|Optional Pointers#}.
</li>
<li>Supports {#link|Type Coercion#} to and from integers.</li>
<li>Supports comparison with integers.</li>
<li>Does not support Zig-only pointer attributes such as alignment. Use normal {#link|Pointers#}
please!</li>
</ul>
<p>When a C pointer is pointing to a single struct (not an array), dereference the C pointer to
access the struct's fields or member data. That syntax looks like
this: </p>
<p>{#syntax#}ptr_to_struct.*.struct_member{#endsyntax#}</p>
<p>This is comparable to doing {#syntax#}->{#endsyntax#} in C.</p>
<p> When a C pointer is pointing to an array of structs, the syntax reverts to this:</p>
<p>{#syntax#}ptr_to_struct_array[index].struct_member{#endsyntax#}</p>
{#header_close#}
{#header_open|C Variadic Functions#}
<p>Zig supports extern variadic functions.</p>
{#code_begin|test|test_variadic_function#}
{#link_libc#}
{#code_verbose_cimport#}
const std = @import("std");
const testing = std.testing;
pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
test "variadic function" {
try testing.expect(printf("Hello, world!\n") == 14);
try testing.expect(@typeInfo(@TypeOf(printf)).Fn.is_var_args);
}
{#code_end#}
<p>
Variadic functions can be implemented using {#link|@cVaStart#}, {#link|@cVaEnd#}, {#link|@cVaArg#} and {#link|@cVaCopy#}.
</p>
{#code_begin|test|test_defining_variadic_function#}
const std = @import("std");
const testing = std.testing;
const builtin = @import("builtin");
fn add(count: c_int, ...) callconv(.C) c_int {
var ap = @cVaStart();
defer @cVaEnd(&ap);
var i: usize = 0;
var sum: c_int = 0;
while (i < count) : (i += 1) {
sum += @cVaArg(&ap, c_int);
}
return sum;
}
test "defining a variadic function" {
// Variadic functions are currently disabled on some targets due to miscompilations.
if (builtin.cpu.arch == .aarch64 and builtin.os.tag != .windows and builtin.os.tag != .macos) return error.SkipZigTest;
if (builtin.cpu.arch == .x86_64 and builtin.os.tag == .windows) return error.SkipZigTest;
try std.testing.expectEqual(@as(c_int, 0), add(0));
try std.testing.expectEqual(@as(c_int, 1), add(1, @as(c_int, 1)));
try std.testing.expectEqual(@as(c_int, 3), add(2, @as(c_int, 1), @as(c_int, 2)));
}
{#code_end#}
{#header_close#}
{#header_open|Exporting a C Library#}
<p>
One of the primary use cases for Zig is exporting a library with the C ABI for other programming languages
to call into. The {#syntax#}export{#endsyntax#} keyword in front of functions, variables, and types causes them to
be part of the library API:
</p>
{#code_begin|syntax|mathtest#}
export fn add(a: i32, b: i32) i32 {
return a + b;
}
{#code_end#}
<p>To make a static library:</p>
{#shell_samp#}$ zig build-lib mathtest.zig{#end_shell_samp#}
<p>To make a shared library:</p>
{#shell_samp#}$ zig build-lib mathtest.zig -dynamic{#end_shell_samp#}
<p>Here is an example with the {#link|Zig Build System#}:</p>
{#syntax_block|c|test.c#}
// This header is generated by zig from mathtest.zig
#include "mathtest.h"
#include <stdio.h>
int main(int argc, char **argv) {
int32_t result = add(42, 1337);
printf("%d\n", result);
return 0;
}
{#end_syntax_block#}
{#code_begin|syntax|build_c#}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0));
const exe = b.addExecutable("test", null);
exe.addCSourceFile("test.c", &[_][]const u8{"-std=c99"});
exe.linkLibrary(lib);
exe.linkSystemLibrary("c");
b.default_step.dependOn(&exe.step);
const run_cmd = exe.run();
const test_step = b.step("test", "Test the program");
test_step.dependOn(&run_cmd.step);
}
{#code_end#}
{#shell_samp#}$ zig build test
1379{#end_shell_samp#}
{#see_also|export#}
{#header_close#}
{#header_open|Mixing Object Files#}
<p>
You can mix Zig object files with any other object files that respect the C ABI. Example:
</p>
{#code_begin|syntax|base64#}
const base64 = @import("std").base64;
export fn decode_base_64(
dest_ptr: [*]u8,
dest_len: usize,
source_ptr: [*]const u8,
source_len: usize,
) usize {
const src = source_ptr[0..source_len];
const dest = dest_ptr[0..dest_len];
const base64_decoder = base64.standard.Decoder;
const decoded_size = base64_decoder.calcSizeForSlice(src) catch unreachable;
base64_decoder.decode(dest[0..decoded_size], src) catch unreachable;
return decoded_size;
}
{#code_end#}
{#syntax_block|c|test.c#}
// This header is generated by zig from base64.zig
#include "base64.h"
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv) {
const char *encoded = "YWxsIHlvdXIgYmFzZSBhcmUgYmVsb25nIHRvIHVz";
char buf[200];
size_t len = decode_base_64(buf, 200, encoded, strlen(encoded));
buf[len] = 0;
puts(buf);
return 0;
}
{#end_syntax_block#}
{#code_begin|syntax|build_object#}
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const obj = b.addObject("base64", "base64.zig");
const exe = b.addExecutable("test", null);
exe.addCSourceFile("test.c", &[_][]const u8{"-std=c99"});
exe.addObject(obj);
exe.linkSystemLibrary("c");
exe.install();
}
{#code_end#}
{#shell_samp#}$ zig build
$ ./zig-out/bin/test
all your base are belong to us{#end_shell_samp#}
{#see_also|Targets|Zig Build System#}
{#header_close#}
{#header_close#}
{#header_open|WebAssembly#}
<p>Zig supports building for WebAssembly out of the box.</p>
{#header_open|Freestanding#}
<p>For host environments like the web browser and nodejs, build as a dynamic library using the freestanding
OS target. Here's an example of running Zig code compiled to WebAssembly with nodejs.</p>
{#code_begin|lib|math#}
{#target_wasm#}
{#link_mode_dynamic#}
extern fn print(i32) void;
export fn add(a: i32, b: i32) void {
print(a + b);
}
{#code_end#}
{#syntax_block|javascript|test.js#}
const fs = require('fs');
const source = fs.readFileSync("./math.wasm");
const typedArray = new Uint8Array(source);
WebAssembly.instantiate(typedArray, {
env: {
print: (result) => { console.log(`The result is ${result}`); }
}}).then(result => {
const add = result.instance.exports.add;
add(1, 2);
});
{#end_syntax_block#}
{#shell_samp#}$ node test.js
The result is 3{#end_shell_samp#}
{#header_close#}
{#header_open|WASI#}
<p>Zig's support for WebAssembly System Interface (WASI) is under active development.
Example of using the standard library and reading command line arguments:</p>
{#code_begin|exe|wasi_args#}
{#target_wasi#}
const std = @import("std");
pub fn main() !void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = general_purpose_allocator.allocator();
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);
for (args) |arg, i| {
std.debug.print("{}: {s}\n", .{ i, arg });
}
}
{#code_end#}
{#shell_samp#}$ wasmtime args.wasm 123 hello
0: args.wasm
1: 123
2: hello{#end_shell_samp#}
<p>A more interesting example would be extracting the list of preopens from the runtime.
This is now supported in the standard library via {#syntax#}std.fs.wasi.PreopenList{#endsyntax#}:</p>
{#code_begin|exe|wasi_preopens#}
{#target_wasi#}
const std = @import("std");
const fs = std.fs;
pub fn main() !void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = general_purpose_allocator.allocator();
var arena_instance = std.heap.ArenaAllocator.init(gpa);
defer arena_instance.deinit();
const arena = arena_instance.allocator();
const preopens = try fs.wasi.preopensAlloc(arena);
for (preopens.names) |preopen, i| {
std.debug.print("{}: {s}\n", .{ i, preopen });
}
}
{#code_end#}
{#shell_samp#}$ wasmtime --dir=. preopens.wasm
0: stdin
1: stdout
2: stderr
3: .
{#end_shell_samp#}
{#header_close#}
{#header_close#}
{#header_open|Targets#}
<p>
Zig supports generating code for all targets that LLVM supports. Here is
what it looks like to execute <code>zig targets</code> on a Linux x86_64
computer:
</p>
{#shell_samp#}$ zig targets
Architectures:
arm
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
armeb
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
aarch64
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
aarch64_be
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
avr
bpfel
bpfeb
hexagon
mips
mipsel
mips64
mips64el
msp430
powerpc
powerpc64
powerpc64le
r600
amdgcn
riscv32
riscv64
sparc
sparc64
sparcel
s390x
thumb
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
thumbeb
v8_4a
v8_3a
v8_2a
v8_1a
v8
v8r
v8m_baseline
v8m_mainline
v7
v7em
v7m
v7s
v7k
v7ve
v6
v6m
v6k
v6t2
v5
v5te
v4t
x86
x86_64 (native)
xcore
nvptx
nvptx64
lanai
wasm32
wasm64
Operating Systems:
freestanding
ananas
cloudabi
dragonfly
freebsd
fuchsia
ios
kfreebsd
linux (native)
lv2
macos
netbsd
openbsd
solaris
windows
haiku
minix
rtems
nacl
cnk
aix
cuda
nvcl
amdhsa
ps4
elfiamcu
tvos
wasi
watchos
mesa3d
contiki
amdpal
zen
uefi
C ABIs:
none
gnu (native)
gnuabin32
gnuabi64
gnueabi
gnueabihf
gnux32
code16
eabi
eabihf
android
musl
musleabi
musleabihf
msvc
itanium
cygnus
coreclr
simulator
Available libcs:
aarch64_be-linux-gnu
aarch64_be-linux-musl
aarch64-linux-gnu
aarch64-linux-musleabi
armeb-linux-gnueabi
armeb-linux-gnueabihf
armeb-linux-musleabi
armeb-linux-musleabihf
arm-linux-gnueabi
arm-linux-gnueabihf
arm-linux-musleabi
arm-linux-musleabihf
x86-linux-gnu
x86-linux-musl
mips64el-linux-gnuabi64
mips64el-linux-gnuabin32
mips64el-linux-musl
mips64-linux-gnuabi64
mips64-linux-gnuabin32
mips64-linux-musl
mipsel-linux-gnu
mipsel-linux-musl
mips-linux-gnu
mips-linux-musl
nios2-linux-gnu
powerpc64le-linux-gnu
powerpc64le-linux-musl
powerpc64-linux-gnu
powerpc64-linux-musl
powerpc-linux-gnu
powerpc-linux-musl
riscv32-linux-musl
riscv64-linux-gnu
riscv64-linux-musl
s390x-linux-gnu
s390x-linux-musl
sparc-linux-gnu
sparc64-linux-gnu
wasm32-freestanding-musl
wasm32-wasi-musl
x86_64-linux-gnu
x86_64-linux-gnux32
x86_64-linux-musl{#end_shell_samp#}
<p>
The Zig Standard Library ({#syntax#}@import("std"){#endsyntax#}) has architecture, environment, and operating system
abstractions, and thus takes additional work to support more platforms.
Not all standard library code requires operating system abstractions, however,
so things such as generic data structures work on all above platforms.
</p>
<p>The current list of targets supported by the Zig Standard Library is:</p>
<ul>
<li>Linux x86_64</li>
<li>Windows x86_64</li>
<li>macOS x86_64</li>
</ul>
{#header_close#}
{#header_open|Style Guide#}
<p>
These coding conventions are not enforced by the compiler, but they are shipped in
this documentation along with the compiler in order to provide a point of
reference, should anyone wish to point to an authority on agreed upon Zig
coding style.
</p>
{#header_open|Whitespace#}
<ul>
<li>
4 space indentation
</li>
<li>
Open braces on same line, unless you need to wrap.
</li>
<li>If a list of things is longer than 2, put each item on its own line and
exercise the ability to put an extra comma at the end.
</li>
<li>
Line length: aim for 100; use common sense.
</li>
</ul>
{#header_close#}
{#header_open|Names#}
<p>
Roughly speaking: {#syntax#}camelCaseFunctionName{#endsyntax#}, {#syntax#}TitleCaseTypeName{#endsyntax#},
{#syntax#}snake_case_variable_name{#endsyntax#}. More precisely:
</p>
<ul>
<li>
If {#syntax#}x{#endsyntax#} is a {#syntax#}type{#endsyntax#}
then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}, unless it
is a {#syntax#}struct{#endsyntax#} with 0 fields and is never meant to be instantiated,
in which case it is considered to be a "namespace" and uses {#syntax#}snake_case{#endsyntax#}.
</li>
<li>
If {#syntax#}x{#endsyntax#} is callable, and {#syntax#}x{#endsyntax#}'s return type is
{#syntax#}type{#endsyntax#}, then {#syntax#}x{#endsyntax#} should be {#syntax#}TitleCase{#endsyntax#}.
</li>
<li>
If {#syntax#}x{#endsyntax#} is otherwise callable, then {#syntax#}x{#endsyntax#} should
be {#syntax#}camelCase{#endsyntax#}.
</li>
<li>
Otherwise, {#syntax#}x{#endsyntax#} should be {#syntax#}snake_case{#endsyntax#}.
</li>
</ul>
<p>
Acronyms, initialisms, proper nouns, or any other word that has capitalization
rules in written English are subject to naming conventions just like any other
word. Even acronyms that are only 2 letters long are subject to these
conventions.
</p>
<p>
File names fall into two categories: types and namespaces. If the file
(implicitly a struct) has top level fields, it should be named like any
other struct with fields using <code class="file">TitleCase</code>. Otherwise,
it should use <code class="file">snake_case</code>. Directory names should be
<code class="file">snake_case</code>.
</p>
<p>
These are general rules of thumb; if it makes sense to do something different,
do what makes sense. For example, if there is an established convention such as
{#syntax#}ENOENT{#endsyntax#}, follow the established convention.
</p>
{#header_close#}
{#header_open|Examples#}
{#syntax_block|zig|style_example.zig#}
const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
var global_var: i32 = undefined;
const const_name = 42;
const primitive_type_alias = f32;
const string_alias = []u8;
const StructName = struct {
field: i32,
};
const StructAlias = StructName;
fn functionName(param_name: TypeName) void {
var functionPointer = functionName;
functionPointer();
functionPointer = otherFunction;
functionPointer();
}
const functionAlias = functionName;
fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
return List(ChildType, fixed_size);
}
fn ShortList(comptime T: type, comptime n: usize) type {
return struct {
field_name: [n]T,
fn methodName() void {}
};
}
// The word XML loses its casing when used in Zig identifiers.
const xml_document =
\\<?xml version="1.0" encoding="UTF-8"?>
\\<document>
\\</document>
;
const XmlParser = struct {
field: i32,
};
// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}
{#end_syntax_block#}
<p>
See the {#link|Zig Standard Library#} for more examples.
</p>
{#header_close#}
{#header_open|Doc Comment Guidance#}
<ul>
<li>Omit any information that is redundant based on the name of the thing being documented.</li>
<li>Duplicating information onto multiple similar functions is encouraged because it helps IDEs and other tools provide better help text.</li>
<li>Use the word <strong>assume</strong> to indicate invariants that cause {#link|Undefined Behavior#} when violated.</li>
<li>Use the word <strong>assert</strong> to indicate invariants that cause <em>safety-checked</em> {#link|Undefined Behavior#} when violated.</li>
</ul>
{#header_close#}
{#header_close#}
{#header_open|Source Encoding#}
<p>Zig source code is encoded in UTF-8. An invalid UTF-8 byte sequence results in a compile error.</p>
<p>Throughout all zig source code (including in comments), some code points are never allowed:</p>
<ul>
<li>Ascii control characters, except for U+000a (LF), U+000d (CR), and U+0009 (HT): U+0000 - U+0008, U+000b - U+000c, U+000e - U+0001f, U+007f.</li>
<li>Non-Ascii Unicode line endings: U+0085 (NEL), U+2028 (LS), U+2029 (PS).</li>
</ul>
<p>
LF (byte value 0x0a, code point U+000a, {#syntax#}'\n'{#endsyntax#}) is the line terminator in Zig source code.
This byte value terminates every line of zig source code except the last line of the file.
It is recommended that non-empty source files end with an empty line, which means the last byte would be 0x0a (LF).
</p>
<p>
Each LF may be immediately preceded by a single CR (byte value 0x0d, code point U+000d, {#syntax#}'\r'{#endsyntax#})
to form a Windows style line ending, but this is discouraged.
A CR in any other context is not allowed.
</p>
<p>
HT hard tabs (byte value 0x09, code point U+0009, {#syntax#}'\t'{#endsyntax#}) are interchangeable with
SP spaces (byte value 0x20, code point U+0020, {#syntax#}' '{#endsyntax#}) as a token separator,
but use of hard tabs is discouraged. See {#link|Grammar#}.
</p>
<p>
For compatibility with other tools, the compiler ignores a UTF-8-encoded byte order mark (U+FEFF)
if it is the first Unicode code point in the source text. A byte order mark is not allowed anywhere else in the source.
</p>
<p>
Note that running <kbd>zig fmt</kbd> on a source file will implement all recommendations mentioned here.
Note also that the stage1 compiler does <a href="https://github.com/ziglang/zig/wiki/FAQ#why-does-zig-force-me-to-use-spaces-instead-of-tabs">not yet support CR or HT</a> control characters.
</p>
<p>
Note that a tool reading Zig source code can make assumptions if the source code is assumed to be correct Zig code.
For example, when identifying the ends of lines, a tool can use a naive search such as <code>/\n/</code>,
or an <a href="https://msdn.microsoft.com/en-us/library/dd409797.aspx">advanced</a>
search such as <code>/\r\n?|[\n\u0085\u2028\u2029]/</code>, and in either case line endings will be correctly identified.
For another example, when identifying the whitespace before the first token on a line,
a tool can either use a naive search such as <code>/[ \t]/</code>,
or an <a href="https://tc39.es/ecma262/#sec-characterclassescape">advanced</a> search such as <code>/\s/</code>,
and in either case whitespace will be correctly identified.
</p>
{#header_close#}
{#header_open|Keyword Reference#}
<div class="table-wrapper">
<table>
<caption>Keywords</caption>
<thead>
<tr>
<th scope="col">Keyword</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">
<pre>{#syntax#}addrspace{#endsyntax#}</pre>
</th>
<td>
The {#syntax#}addrspace{#endsyntax#} keyword.
<ul>
<li>TODO add documentation for addrspace</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}align{#endsyntax#}</pre>
</th>
<td>
{#syntax#}align{#endsyntax#} can be used to specify the alignment of a pointer.
It can also be used after a variable or function declaration to specify the alignment of pointers to that variable or function.
<ul>
<li>See also {#link|Alignment#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}allowzero{#endsyntax#}</pre>
</th>
<td>
The pointer attribute {#syntax#}allowzero{#endsyntax#} allows a pointer to have address zero.
<ul>
<li>See also {#link|allowzero#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}and{#endsyntax#}</pre>
</th>
<td>
The boolean operator {#syntax#}and{#endsyntax#}.
<ul>
<li>See also {#link|Operators#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}anyframe{#endsyntax#}</pre>
</th>
<td>
{#syntax#}anyframe{#endsyntax#} can be used as a type for variables which hold pointers to function frames.
<ul>
<li>See also {#link|Async Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}anytype{#endsyntax#}</pre>
</th>
<td>
Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type.
The type will be inferred where the function is called.
<ul>
<li>See also {#link|Function Parameter Type Inference#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}asm{#endsyntax#}</pre>
</th>
<td>
{#syntax#}asm{#endsyntax#} begins an inline assembly expression. This allows for directly controlling the machine code generated on compilation.
<ul>
<li>See also {#link|Assembly#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}async{#endsyntax#}</pre>
</th>
<td>
{#syntax#}async{#endsyntax#} can be used before a function call to get a pointer to the function's frame when it suspends.
<ul>
<li>See also {#link|Async Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}await{#endsyntax#}</pre>
</th>
<td>
{#syntax#}await{#endsyntax#} can be used to suspend the current function until the frame provided after the {#syntax#}await{#endsyntax#} completes.
{#syntax#}await{#endsyntax#} copies the value returned from the target function's frame to the caller.
<ul>
<li>See also {#link|Async Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}break{#endsyntax#}</pre>
</th>
<td>
{#syntax#}break{#endsyntax#} can be used with a block label to return a value from the block.
It can also be used to exit a loop before iteration completes naturally.
<ul>
<li>See also {#link|Blocks#}, {#link|while#}, {#link|for#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}catch{#endsyntax#}</pre>
</th>
<td>
{#syntax#}catch{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to an error.
The expression after the {#syntax#}catch{#endsyntax#} can optionally capture the error value.
<ul>
<li>See also {#link|catch#}, {#link|Operators#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}comptime{#endsyntax#}</pre>
</th>
<td>
{#syntax#}comptime{#endsyntax#} before a declaration can be used to label variables or function parameters as known at compile time.
It can also be used to guarantee an expression is run at compile time.
<ul>
<li>See also {#link|comptime#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}const{#endsyntax#}</pre>
</th>
<td>
{#syntax#}const{#endsyntax#} declares a variable that can not be modified.
Used as a pointer attribute, it denotes the value referenced by the pointer cannot be modified.
<ul>
<li>See also {#link|Variables#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}continue{#endsyntax#}</pre>
</th>
<td>
{#syntax#}continue{#endsyntax#} can be used in a loop to jump back to the beginning of the loop.
<ul>
<li>See also {#link|while#}, {#link|for#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}defer{#endsyntax#}</pre>
</th>
<td>
{#syntax#}defer{#endsyntax#} will execute an expression when control flow leaves the current block.
<ul>
<li>See also {#link|defer#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}else{#endsyntax#}</pre>
</th>
<td>
{#syntax#}else{#endsyntax#} can be used to provide an alternate branch for {#syntax#}if{#endsyntax#}, {#syntax#}switch{#endsyntax#},
{#syntax#}while{#endsyntax#}, and {#syntax#}for{#endsyntax#} expressions.
<ul>
<li>If used after an if expression, the else branch will be executed if the test value returns false, null, or an error.</li>
<li>If used within a switch expression, the else branch will be executed if the test value matches no other cases.</li>
<li>If used after a loop expression, the else branch will be executed if the loop finishes without breaking.</li>
<li>See also {#link|if#}, {#link|switch#}, {#link|while#}, {#link|for#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}enum{#endsyntax#}</pre>
</th>
<td>
{#syntax#}enum{#endsyntax#} defines an enum type.
<ul>
<li>See also {#link|enum#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}errdefer{#endsyntax#}</pre>
</th>
<td>
{#syntax#}errdefer{#endsyntax#} will execute an expression when control flow leaves the current block if the function returns an error, the errdefer expression can capture the unwrapped value.
<ul>
<li>See also {#link|errdefer#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}error{#endsyntax#}</pre>
</th>
<td>
{#syntax#}error{#endsyntax#} defines an error type.
<ul>
<li>See also {#link|Errors#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}export{#endsyntax#}</pre>
</th>
<td>
{#syntax#}export{#endsyntax#} makes a function or variable externally visible in the generated object file.
Exported functions default to the C calling convention.
<ul>
<li>See also {#link|Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}extern{#endsyntax#}</pre>
</th>
<td>
{#syntax#}extern{#endsyntax#} can be used to declare a function or variable that will be resolved at link time, when linking statically
or at runtime, when linking dynamically.
<ul>
<li>See also {#link|Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}fn{#endsyntax#}</pre>
</th>
<td>
{#syntax#}fn{#endsyntax#} declares a function.
<ul>
<li>See also {#link|Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}for{#endsyntax#}</pre>
</th>
<td>
A {#syntax#}for{#endsyntax#} expression can be used to iterate over the elements of a slice, array, or tuple.
<ul>
<li>See also {#link|for#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}if{#endsyntax#}</pre>
</th>
<td>
An {#syntax#}if{#endsyntax#} expression can test boolean expressions, optional values, or error unions.
For optional values or error unions, the if expression can capture the unwrapped value.
<ul>
<li>See also {#link|if#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}inline{#endsyntax#}</pre>
</th>
<td>
{#syntax#}inline{#endsyntax#} can be used to label a loop expression such that it will be unrolled at compile time.
It can also be used to force a function to be inlined at all call sites.
<ul>
<li>See also {#link|inline while#}, {#link|inline for#}, {#link|Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}linksection{#endsyntax#}</pre>
</th>
<td>
The {#syntax#}linksection{#endsyntax#} keyword.
<ul>
<li>TODO add documentation for linksection</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}noalias{#endsyntax#}</pre>
</th>
<td>
The {#syntax#}noalias{#endsyntax#} keyword.
<ul>
<li>TODO add documentation for noalias</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}nosuspend{#endsyntax#}</pre>
</th>
<td>
The {#syntax#}nosuspend{#endsyntax#} keyword can be used in front of a block, statement or expression, to mark a scope where no suspension points are reached.
In particular, inside a {#syntax#}nosuspend{#endsyntax#} scope:
<ul>
<li>Using the {#syntax#}suspend{#endsyntax#} keyword results in a compile error.</li>
<li>Using {#syntax#}await{#endsyntax#} on a function frame which hasn't completed yet results in safety-checked {#link|Undefined Behavior#}.</li>
<li>Calling an async function may result in safety-checked {#link|Undefined Behavior#}, because it's equivalent to <code>await async some_async_fn()</code>, which contains an {#syntax#}await{#endsyntax#}.</li>
</ul>
Code inside a {#syntax#}nosuspend{#endsyntax#} scope does not cause the enclosing function to become an {#link|async function|Async Functions#}.
<ul>
<li>See also {#link|Async Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}or{#endsyntax#}</pre>
</th>
<td>
The boolean operator {#syntax#}or{#endsyntax#}.
<ul>
<li>See also {#link|Operators#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}orelse{#endsyntax#}</pre>
</th>
<td>
{#syntax#}orelse{#endsyntax#} can be used to evaluate an expression if the expression before it evaluates to null.
<ul>
<li>See also {#link|Optionals#}, {#link|Operators#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}packed{#endsyntax#}</pre>
</th>
<td>
The {#syntax#}packed{#endsyntax#} keyword before a struct definition changes the struct's in-memory layout
to the guaranteed {#syntax#}packed{#endsyntax#} layout.
<ul>
<li>See also {#link|packed struct#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}pub{#endsyntax#}</pre>
</th>
<td>
The {#syntax#}pub{#endsyntax#} in front of a top level declaration makes the declaration available
to reference from a different file than the one it is declared in.
<ul>
<li>See also {#link|import#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}resume{#endsyntax#}</pre>
</th>
<td>
{#syntax#}resume{#endsyntax#} will continue execution of a function frame after the point the function was suspended.
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}return{#endsyntax#}</pre>
</th>
<td>
{#syntax#}return{#endsyntax#} exits a function with a value.
<ul>
<li>See also {#link|Functions#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}struct{#endsyntax#}</pre>
</th>
<td>
{#syntax#}struct{#endsyntax#} defines a struct.
<ul>
<li>See also {#link|struct#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}suspend{#endsyntax#}</pre>
</th>
<td>
{#syntax#}suspend{#endsyntax#} will cause control flow to return to the call site or resumer of the function.
{#syntax#}suspend{#endsyntax#} can also be used before a block within a function,
to allow the function access to its frame before control flow returns to the call site.
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}switch{#endsyntax#}</pre>
</th>
<td>
A {#syntax#}switch{#endsyntax#} expression can be used to test values of a common type.
{#syntax#}switch{#endsyntax#} cases can capture field values of a {#link|Tagged union#}.
<ul>
<li>See also {#link|switch#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}test{#endsyntax#}</pre>
</th>
<td>
The {#syntax#}test{#endsyntax#} keyword can be used to denote a top-level block of code
used to make sure behavior meets expectations.
<ul>
<li>See also {#link|Zig Test#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}threadlocal{#endsyntax#}</pre>
</th>
<td>
{#syntax#}threadlocal{#endsyntax#} can be used to specify a variable as thread-local.
<ul>
<li>See also {#link|Thread Local Variables#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}try{#endsyntax#}</pre>
</th>
<td>
{#syntax#}try{#endsyntax#} evaluates an error union expression.
If it is an error, it returns from the current function with the same error.
Otherwise, the expression results in the unwrapped value.
<ul>
<li>See also {#link|try#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}union{#endsyntax#}</pre>
</th>
<td>
{#syntax#}union{#endsyntax#} defines a union.
<ul>
<li>See also {#link|union#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}unreachable{#endsyntax#}</pre>
</th>
<td>
{#syntax#}unreachable{#endsyntax#} can be used to assert that control flow will never happen upon a particular location.
Depending on the build mode, {#syntax#}unreachable{#endsyntax#} may emit a panic.
<ul>
<li>Emits a panic in {#syntax#}Debug{#endsyntax#} and {#syntax#}ReleaseSafe{#endsyntax#} mode, or when using <kbd>zig test</kbd>.</li>
<li>Does not emit a panic in {#syntax#}ReleaseFast{#endsyntax#} and {#syntax#}ReleaseSmall{#endsyntax#} mode.</li>
<li>See also {#link|unreachable#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}usingnamespace{#endsyntax#}</pre>
</th>
<td>
{#syntax#}usingnamespace{#endsyntax#} is a top-level declaration that imports all the public declarations of the operand,
which must be a struct, union, or enum, into the current scope.
<ul>
<li>See also {#link|usingnamespace#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}var{#endsyntax#}</pre>
</th>
<td>
{#syntax#}var{#endsyntax#} declares a variable that may be modified.
<ul>
<li>See also {#link|Variables#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}volatile{#endsyntax#}</pre>
</th>
<td>
{#syntax#}volatile{#endsyntax#} can be used to denote loads or stores of a pointer have side effects.
It can also modify an inline assembly expression to denote it has side effects.
<ul>
<li>See also {#link|volatile#}, {#link|Assembly#}</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">
<pre>{#syntax#}while{#endsyntax#}</pre>
</th>
<td>
A {#syntax#}while{#endsyntax#} expression can be used to repeatedly test a boolean, optional, or error union expression,
and cease looping when that expression evaluates to false, null, or an error, respectively.
<ul>
<li>See also {#link|while#}</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
{#header_close#}
{#header_open|Appendix#}
{#header_open|Containers#}
<p>
A <em>container</em> in Zig is any syntactical construct that acts as a namespace to hold {#link|variable|Container Level Variables#} and {#link|function|Functions#} declarations.
Containers are also type definitions which can be instantiated.
{#link|Structs|struct#}, {#link|enums|enum#}, {#link|unions|union#}, {#link|opaques|opaque#}, and even Zig source files themselves are containers.
</p>
<p>
Although containers (except Zig source files) use curly braces to surround their definition, they should not be confused with {#link|blocks|Blocks#} or functions.
Containers do not contain statements.
</p>
{#header_close#}
{#header_open|Grammar#}
{#syntax_block|peg|grammar.y#}
Root <- skip container_doc_comment? ContainerMembers eof
# *** Top level ***
ContainerMembers <- ContainerDeclarations (ContainerField COMMA)* (ContainerField / ContainerDeclarations)
ContainerDeclarations
<- TestDecl ContainerDeclarations
/ ComptimeDecl ContainerDeclarations
/ doc_comment? KEYWORD_pub? Decl ContainerDeclarations
/
TestDecl <- KEYWORD_test (STRINGLITERALSINGLE / IDENTIFIER)? Block
ComptimeDecl <- KEYWORD_comptime Block
Decl
<- (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE? / (KEYWORD_inline / KEYWORD_noinline))? FnProto (SEMICOLON / Block)
/ (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? VarDecl
/ KEYWORD_usingnamespace Expr SEMICOLON
FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? AddrSpace? LinkSection? CallConv? EXCLAMATIONMARK? TypeExpr
VarDecl <- (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? AddrSpace? LinkSection? (EQUAL Expr)? SEMICOLON
ContainerField
<- doc_comment? KEYWORD_comptime? IDENTIFIER (COLON TypeExpr)? ByteAlign? (EQUAL Expr)?
/ doc_comment? KEYWORD_comptime? (IDENTIFIER COLON)? !KEYWORD_fn TypeExpr ByteAlign? (EQUAL Expr)?
# *** Block Level ***
Statement
<- KEYWORD_comptime? VarDecl
/ KEYWORD_comptime BlockExprStatement
/ KEYWORD_nosuspend BlockExprStatement
/ KEYWORD_suspend BlockExprStatement
/ KEYWORD_defer BlockExprStatement
/ KEYWORD_errdefer Payload? BlockExprStatement
/ IfStatement
/ LabeledStatement
/ SwitchExpr
/ AssignExpr SEMICOLON
IfStatement
<- IfPrefix BlockExpr ( KEYWORD_else Payload? Statement )?
/ IfPrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement )
LabeledStatement <- BlockLabel? (Block / LoopStatement)
LoopStatement <- KEYWORD_inline? (ForStatement / WhileStatement)
ForStatement
<- ForPrefix BlockExpr ( KEYWORD_else Statement )?
/ ForPrefix AssignExpr ( SEMICOLON / KEYWORD_else Statement )
WhileStatement
<- WhilePrefix BlockExpr ( KEYWORD_else Payload? Statement )?
/ WhilePrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement )
BlockExprStatement
<- BlockExpr
/ AssignExpr SEMICOLON
BlockExpr <- BlockLabel? Block
# *** Expression Level ***
AssignExpr <- Expr (AssignOp Expr)?
Expr <- BoolOrExpr
BoolOrExpr <- BoolAndExpr (KEYWORD_or BoolAndExpr)*
BoolAndExpr <- CompareExpr (KEYWORD_and CompareExpr)*
CompareExpr <- BitwiseExpr (CompareOp BitwiseExpr)?
BitwiseExpr <- BitShiftExpr (BitwiseOp BitShiftExpr)*
BitShiftExpr <- AdditionExpr (BitShiftOp AdditionExpr)*
AdditionExpr <- MultiplyExpr (AdditionOp MultiplyExpr)*
MultiplyExpr <- PrefixExpr (MultiplyOp PrefixExpr)*
PrefixExpr <- PrefixOp* PrimaryExpr
PrimaryExpr
<- AsmExpr
/ IfExpr
/ KEYWORD_break BreakLabel? Expr?
/ KEYWORD_comptime Expr
/ KEYWORD_nosuspend Expr
/ KEYWORD_continue BreakLabel?
/ KEYWORD_resume Expr
/ KEYWORD_return Expr?
/ BlockLabel? LoopExpr
/ Block
/ CurlySuffixExpr
IfExpr <- IfPrefix Expr (KEYWORD_else Payload? Expr)?
Block <- LBRACE Statement* RBRACE
LoopExpr <- KEYWORD_inline? (ForExpr / WhileExpr)
ForExpr <- ForPrefix Expr (KEYWORD_else Expr)?
WhileExpr <- WhilePrefix Expr (KEYWORD_else Payload? Expr)?
CurlySuffixExpr <- TypeExpr InitList?
InitList
<- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE
/ LBRACE Expr (COMMA Expr)* COMMA? RBRACE
/ LBRACE RBRACE
TypeExpr <- PrefixTypeOp* ErrorUnionExpr
ErrorUnionExpr <- SuffixExpr (EXCLAMATIONMARK TypeExpr)?
SuffixExpr
<- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments
/ PrimaryTypeExpr (SuffixOp / FnCallArguments)*
PrimaryTypeExpr
<- BUILTINIDENTIFIER FnCallArguments
/ CHAR_LITERAL
/ ContainerDecl
/ DOT IDENTIFIER
/ DOT InitList
/ ErrorSetDecl
/ FLOAT
/ FnProto
/ GroupedExpr
/ LabeledTypeExpr
/ IDENTIFIER
/ IfTypeExpr
/ INTEGER
/ KEYWORD_comptime TypeExpr
/ KEYWORD_error DOT IDENTIFIER
/ KEYWORD_anyframe
/ KEYWORD_unreachable
/ STRINGLITERAL
/ SwitchExpr
ContainerDecl <- (KEYWORD_extern / KEYWORD_packed)? ContainerDeclAuto
ErrorSetDecl <- KEYWORD_error LBRACE IdentifierList RBRACE
GroupedExpr <- LPAREN Expr RPAREN
IfTypeExpr <- IfPrefix TypeExpr (KEYWORD_else Payload? TypeExpr)?
LabeledTypeExpr
<- BlockLabel Block
/ BlockLabel? LoopTypeExpr
LoopTypeExpr <- KEYWORD_inline? (ForTypeExpr / WhileTypeExpr)
ForTypeExpr <- ForPrefix TypeExpr (KEYWORD_else TypeExpr)?
WhileTypeExpr <- WhilePrefix TypeExpr (KEYWORD_else Payload? TypeExpr)?
SwitchExpr <- KEYWORD_switch LPAREN Expr RPAREN LBRACE SwitchProngList RBRACE
# *** Assembly ***
AsmExpr <- KEYWORD_asm KEYWORD_volatile? LPAREN Expr AsmOutput? RPAREN
AsmOutput <- COLON AsmOutputList AsmInput?
AsmOutputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN (MINUSRARROW TypeExpr / IDENTIFIER) RPAREN
AsmInput <- COLON AsmInputList AsmClobbers?
AsmInputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN Expr RPAREN
AsmClobbers <- COLON StringList
# *** Helper grammar ***
BreakLabel <- COLON IDENTIFIER
BlockLabel <- IDENTIFIER COLON
FieldInit <- DOT IDENTIFIER EQUAL Expr
WhileContinueExpr <- COLON LPAREN AssignExpr RPAREN
LinkSection <- KEYWORD_linksection LPAREN Expr RPAREN
AddrSpace <- KEYWORD_addrspace LPAREN Expr RPAREN
# Fn specific
CallConv <- KEYWORD_callconv LPAREN Expr RPAREN
ParamDecl
<- doc_comment? (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType
/ DOT3
ParamType
<- KEYWORD_anytype
/ TypeExpr
# Control flow prefixes
IfPrefix <- KEYWORD_if LPAREN Expr RPAREN PtrPayload?
WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr?
ForPrefix <- KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload
# Payloads
Payload <- PIPE IDENTIFIER PIPE
PtrPayload <- PIPE ASTERISK? IDENTIFIER PIPE
PtrIndexPayload <- PIPE ASTERISK? IDENTIFIER (COMMA IDENTIFIER)? PIPE
# Switch specific
SwitchProng <- KEYWORD_inline? SwitchCase EQUALRARROW PtrIndexPayload? AssignExpr
SwitchCase
<- SwitchItem (COMMA SwitchItem)* COMMA?
/ KEYWORD_else
SwitchItem <- Expr (DOT3 Expr)?
# Operators
AssignOp
<- ASTERISKEQUAL
/ ASTERISKPIPEEQUAL
/ SLASHEQUAL
/ PERCENTEQUAL
/ PLUSEQUAL
/ PLUSPIPEEQUAL
/ MINUSEQUAL
/ MINUSPIPEEQUAL
/ LARROW2EQUAL
/ LARROW2PIPEEQUAL
/ RARROW2EQUAL
/ AMPERSANDEQUAL
/ CARETEQUAL
/ PIPEEQUAL
/ ASTERISKPERCENTEQUAL
/ PLUSPERCENTEQUAL
/ MINUSPERCENTEQUAL
/ EQUAL
CompareOp
<- EQUALEQUAL
/ EXCLAMATIONMARKEQUAL
/ LARROW
/ RARROW
/ LARROWEQUAL
/ RARROWEQUAL
BitwiseOp
<- AMPERSAND
/ CARET
/ PIPE
/ KEYWORD_orelse
/ KEYWORD_catch Payload?
BitShiftOp
<- LARROW2
/ RARROW2
/ LARROW2PIPE
AdditionOp
<- PLUS
/ MINUS
/ PLUS2
/ PLUSPERCENT
/ MINUSPERCENT
/ PLUSPIPE
/ MINUSPIPE
MultiplyOp
<- PIPE2
/ ASTERISK
/ SLASH
/ PERCENT
/ ASTERISK2
/ ASTERISKPERCENT
/ ASTERISKPIPE
PrefixOp
<- EXCLAMATIONMARK
/ MINUS
/ TILDE
/ MINUSPERCENT
/ AMPERSAND
/ KEYWORD_try
/ KEYWORD_await
PrefixTypeOp
<- QUESTIONMARK
/ KEYWORD_anyframe MINUSRARROW
/ SliceTypeStart (ByteAlign / AddrSpace / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)*
/ PtrTypeStart (AddrSpace / KEYWORD_align LPAREN Expr (COLON Expr COLON Expr)? RPAREN / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)*
/ ArrayTypeStart
SuffixOp
<- LBRACKET Expr (DOT2 (Expr? (COLON Expr)?)?)? RBRACKET
/ DOT IDENTIFIER
/ DOTASTERISK
/ DOTQUESTIONMARK
FnCallArguments <- LPAREN ExprList RPAREN
# Ptr specific
SliceTypeStart <- LBRACKET (COLON Expr)? RBRACKET
PtrTypeStart
<- ASTERISK
/ ASTERISK2
/ LBRACKET ASTERISK (LETTERC / COLON Expr)? RBRACKET
ArrayTypeStart <- LBRACKET Expr (COLON Expr)? RBRACKET
# ContainerDecl specific
ContainerDeclAuto <- ContainerDeclType LBRACE container_doc_comment? ContainerMembers RBRACE
ContainerDeclType
<- KEYWORD_struct (LPAREN Expr RPAREN)?
/ KEYWORD_opaque
/ KEYWORD_enum (LPAREN Expr RPAREN)?
/ KEYWORD_union (LPAREN (KEYWORD_enum (LPAREN Expr RPAREN)? / Expr) RPAREN)?
# Alignment
ByteAlign <- KEYWORD_align LPAREN Expr RPAREN
# Lists
IdentifierList <- (doc_comment? IDENTIFIER COMMA)* (doc_comment? IDENTIFIER)?
SwitchProngList <- (SwitchProng COMMA)* SwitchProng?
AsmOutputList <- (AsmOutputItem COMMA)* AsmOutputItem?
AsmInputList <- (AsmInputItem COMMA)* AsmInputItem?
StringList <- (STRINGLITERAL COMMA)* STRINGLITERAL?
ParamDeclList <- (ParamDecl COMMA)* ParamDecl?
ExprList <- (Expr COMMA)* Expr?
# *** Tokens ***
eof <- !.
bin <- [01]
bin_ <- '_'? bin
oct <- [0-7]
oct_ <- '_'? oct
hex <- [0-9a-fA-F]
hex_ <- '_'? hex
dec <- [0-9]
dec_ <- '_'? dec
bin_int <- bin bin_*
oct_int <- oct oct_*
dec_int <- dec dec_*
hex_int <- hex hex_*
ox80_oxBF <- [\200-\277]
oxF4 <- '\364'
ox80_ox8F <- [\200-\217]
oxF1_oxF3 <- [\361-\363]
oxF0 <- '\360'
ox90_0xBF <- [\220-\277]
oxEE_oxEF <- [\356-\357]
oxED <- '\355'
ox80_ox9F <- [\200-\237]
oxE1_oxEC <- [\341-\354]
oxE0 <- '\340'
oxA0_oxBF <- [\240-\277]
oxC2_oxDF <- [\302-\337]
# From https://lemire.me/blog/2018/05/09/how-quickly-can-you-check-that-a-string-is-valid-unicode-utf-8/
# First Byte Second Byte Third Byte Fourth Byte
# [0x00,0x7F]
# [0xC2,0xDF] [0x80,0xBF]
# 0xE0 [0xA0,0xBF] [0x80,0xBF]
# [0xE1,0xEC] [0x80,0xBF] [0x80,0xBF]
# 0xED [0x80,0x9F] [0x80,0xBF]
# [0xEE,0xEF] [0x80,0xBF] [0x80,0xBF]
# 0xF0 [0x90,0xBF] [0x80,0xBF] [0x80,0xBF]
# [0xF1,0xF3] [0x80,0xBF] [0x80,0xBF] [0x80,0xBF]
# 0xF4 [0x80,0x8F] [0x80,0xBF] [0x80,0xBF]
mb_utf8_literal <-
oxF4 ox80_ox8F ox80_oxBF ox80_oxBF
/ oxF1_oxF3 ox80_oxBF ox80_oxBF ox80_oxBF
/ oxF0 ox90_0xBF ox80_oxBF ox80_oxBF
/ oxEE_oxEF ox80_oxBF ox80_oxBF
/ oxED ox80_ox9F ox80_oxBF
/ oxE1_oxEC ox80_oxBF ox80_oxBF
/ oxE0 oxA0_oxBF ox80_oxBF
/ oxC2_oxDF ox80_oxBF
ascii_char_not_nl_slash_squote <- [\000-\011\013-\046-\050-\133\135-\177]
char_escape
<- "\\x" hex hex
/ "\\u{" hex+ "}"
/ "\\" [nr\\t'"]
char_char
<- mb_utf8_literal
/ char_escape
/ ascii_char_not_nl_slash_squote
string_char
<- char_escape
/ [^\\"\n]
container_doc_comment <- ('//!' [^\n]* [ \n]* skip)+
doc_comment <- ('///' [^\n]* [ \n]* skip)+
line_comment <- '//' ![!/][^\n]* / '////' [^\n]*
line_string <- ("\\\\" [^\n]* [ \n]*)+
skip <- ([ \n] / line_comment)*
CHAR_LITERAL <- "'" char_char "'" skip
FLOAT
<- "0x" hex_int "." hex_int ([pP] [-+]? dec_int)? skip
/ dec_int "." dec_int ([eE] [-+]? dec_int)? skip
/ "0x" hex_int [pP] [-+]? dec_int skip
/ dec_int [eE] [-+]? dec_int skip
INTEGER
<- "0b" bin_int skip
/ "0o" oct_int skip
/ "0x" hex_int skip
/ dec_int skip
STRINGLITERALSINGLE <- "\"" string_char* "\"" skip
STRINGLITERAL
<- STRINGLITERALSINGLE
/ (line_string skip)+
IDENTIFIER
<- !keyword [A-Za-z_] [A-Za-z0-9_]* skip
/ "@\"" string_char* "\"" skip
BUILTINIDENTIFIER <- "@"[A-Za-z_][A-Za-z0-9_]* skip
AMPERSAND <- '&' ![=] skip
AMPERSANDEQUAL <- '&=' skip
ASTERISK <- '*' ![*%=|] skip
ASTERISK2 <- '**' skip
ASTERISKEQUAL <- '*=' skip
ASTERISKPERCENT <- '*%' ![=] skip
ASTERISKPERCENTEQUAL <- '*%=' skip
ASTERISKPIPE <- '*|' ![=] skip
ASTERISKPIPEEQUAL <- '*|=' skip
CARET <- '^' ![=] skip
CARETEQUAL <- '^=' skip
COLON <- ':' skip
COMMA <- ',' skip
DOT <- '.' ![*.?] skip
DOT2 <- '..' ![.] skip
DOT3 <- '...' skip
DOTASTERISK <- '.*' skip
DOTQUESTIONMARK <- '.?' skip
EQUAL <- '=' ![>=] skip
EQUALEQUAL <- '==' skip
EQUALRARROW <- '=>' skip
EXCLAMATIONMARK <- '!' ![=] skip
EXCLAMATIONMARKEQUAL <- '!=' skip
LARROW <- '<' ![<=] skip
LARROW2 <- '<<' ![=|] skip
LARROW2EQUAL <- '<<=' skip
LARROW2PIPE <- '<<|' ![=] skip
LARROW2PIPEEQUAL <- '<<|=' skip
LARROWEQUAL <- '<=' skip
LBRACE <- '{' skip
LBRACKET <- '[' skip
LPAREN <- '(' skip
MINUS <- '-' ![%=>|] skip
MINUSEQUAL <- '-=' skip
MINUSPERCENT <- '-%' ![=] skip
MINUSPERCENTEQUAL <- '-%=' skip
MINUSPIPE <- '-|' ![=] skip
MINUSPIPEEQUAL <- '-|=' skip
MINUSRARROW <- '->' skip
PERCENT <- '%' ![=] skip
PERCENTEQUAL <- '%=' skip
PIPE <- '|' ![|=] skip
PIPE2 <- '||' skip
PIPEEQUAL <- '|=' skip
PLUS <- '+' ![%+=|] skip
PLUS2 <- '++' skip
PLUSEQUAL <- '+=' skip
PLUSPERCENT <- '+%' ![=] skip
PLUSPERCENTEQUAL <- '+%=' skip
PLUSPIPE <- '+|' ![=] skip
PLUSPIPEEQUAL <- '+|=' skip
LETTERC <- 'c' skip
QUESTIONMARK <- '?' skip
RARROW <- '>' ![>=] skip
RARROW2 <- '>>' ![=] skip
RARROW2EQUAL <- '>>=' skip
RARROWEQUAL <- '>=' skip
RBRACE <- '}' skip
RBRACKET <- ']' skip
RPAREN <- ')' skip
SEMICOLON <- ';' skip
SLASH <- '/' ![=] skip
SLASHEQUAL <- '/=' skip
TILDE <- '~' skip
end_of_word <- ![a-zA-Z0-9_] skip
KEYWORD_addrspace <- 'addrspace' end_of_word
KEYWORD_align <- 'align' end_of_word
KEYWORD_allowzero <- 'allowzero' end_of_word
KEYWORD_and <- 'and' end_of_word
KEYWORD_anyframe <- 'anyframe' end_of_word
KEYWORD_anytype <- 'anytype' end_of_word
KEYWORD_asm <- 'asm' end_of_word
KEYWORD_async <- 'async' end_of_word
KEYWORD_await <- 'await' end_of_word
KEYWORD_break <- 'break' end_of_word
KEYWORD_callconv <- 'callconv' end_of_word
KEYWORD_catch <- 'catch' end_of_word
KEYWORD_comptime <- 'comptime' end_of_word
KEYWORD_const <- 'const' end_of_word
KEYWORD_continue <- 'continue' end_of_word
KEYWORD_defer <- 'defer' end_of_word
KEYWORD_else <- 'else' end_of_word
KEYWORD_enum <- 'enum' end_of_word
KEYWORD_errdefer <- 'errdefer' end_of_word
KEYWORD_error <- 'error' end_of_word
KEYWORD_export <- 'export' end_of_word
KEYWORD_extern <- 'extern' end_of_word
KEYWORD_fn <- 'fn' end_of_word
KEYWORD_for <- 'for' end_of_word
KEYWORD_if <- 'if' end_of_word
KEYWORD_inline <- 'inline' end_of_word
KEYWORD_noalias <- 'noalias' end_of_word
KEYWORD_nosuspend <- 'nosuspend' end_of_word
KEYWORD_noinline <- 'noinline' end_of_word
KEYWORD_opaque <- 'opaque' end_of_word
KEYWORD_or <- 'or' end_of_word
KEYWORD_orelse <- 'orelse' end_of_word
KEYWORD_packed <- 'packed' end_of_word
KEYWORD_pub <- 'pub' end_of_word
KEYWORD_resume <- 'resume' end_of_word
KEYWORD_return <- 'return' end_of_word
KEYWORD_linksection <- 'linksection' end_of_word
KEYWORD_struct <- 'struct' end_of_word
KEYWORD_suspend <- 'suspend' end_of_word
KEYWORD_switch <- 'switch' end_of_word
KEYWORD_test <- 'test' end_of_word
KEYWORD_threadlocal <- 'threadlocal' end_of_word
KEYWORD_try <- 'try' end_of_word
KEYWORD_union <- 'union' end_of_word
KEYWORD_unreachable <- 'unreachable' end_of_word
KEYWORD_usingnamespace <- 'usingnamespace' end_of_word
KEYWORD_var <- 'var' end_of_word
KEYWORD_volatile <- 'volatile' end_of_word
KEYWORD_while <- 'while' end_of_word
keyword <- KEYWORD_addrspace / KEYWORD_align / KEYWORD_allowzero / KEYWORD_and
/ KEYWORD_anyframe / KEYWORD_anytype / KEYWORD_asm / KEYWORD_async
/ KEYWORD_await / KEYWORD_break / KEYWORD_callconv / KEYWORD_catch
/ KEYWORD_comptime / KEYWORD_const / KEYWORD_continue / KEYWORD_defer
/ KEYWORD_else / KEYWORD_enum / KEYWORD_errdefer / KEYWORD_error / KEYWORD_export
/ KEYWORD_extern / KEYWORD_fn / KEYWORD_for / KEYWORD_if
/ KEYWORD_inline / KEYWORD_noalias / KEYWORD_nosuspend / KEYWORD_noinline
/ KEYWORD_opaque / KEYWORD_or / KEYWORD_orelse / KEYWORD_packed
/ KEYWORD_pub / KEYWORD_resume / KEYWORD_return / KEYWORD_linksection
/ KEYWORD_struct / KEYWORD_suspend / KEYWORD_switch / KEYWORD_test
/ KEYWORD_threadlocal / KEYWORD_try / KEYWORD_union / KEYWORD_unreachable
/ KEYWORD_usingnamespace / KEYWORD_var / KEYWORD_volatile / KEYWORD_while
{#end_syntax_block#}
{#header_close#}
{#header_open|Zen#}
<ul>
<li>Communicate intent precisely.</li>
<li>Edge cases matter.</li>
<li>Favor reading code over writing code.</li>
<li>Only one obvious way to do things.</li>
<li>Runtime crashes are better than bugs.</li>
<li>Compile errors are better than runtime crashes.</li>
<li>Incremental improvements.</li>
<li>Avoid local maximums.</li>
<li>Reduce the amount one must remember.</li>
<li>Focus on code rather than style.</li>
<li>Resource allocation may fail; resource deallocation must succeed.</li>
<li>Memory is a resource.</li>
<li>Together we serve the users.</li>
</ul>
{#header_close#}
{#header_close#}
</main></div>
</div>
</body>
</html>
|