Changeset 90152a4 for doc/user/user.tex
- Timestamp:
- Aug 27, 2018, 4:40:34 PM (8 years ago)
- Branches:
- ADT, arm-eh, ast-experimental, cleanup-dtors, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, pthread-emulation, qualifiedEnum, stuck-waitfor-destruct
- Children:
- b7c89aa
- Parents:
- f9feab8 (diff), 305581d (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the(diff)links above to see all the changes relative to each parent. - File:
-
- 1 edited
-
doc/user/user.tex (modified) (84 diffs)
Legend:
- Unmodified
- Added
- Removed
-
doc/user/user.tex
rf9feab8 r90152a4 1 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -*- Mode: Latex -*- %%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 %% 2 %% 3 3 %% Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo 4 4 %% 5 5 %% The contents of this file are covered under the licence agreement in the 6 6 %% file "LICENCE" distributed with Cforall. 7 %% 8 %% user.tex -- 9 %% 7 %% 8 %% user.tex -- 9 %% 10 10 %% Author : Peter A. Buhr 11 11 %% Created On : Wed Apr 6 14:53:29 2016 12 12 %% Last Modified By : Peter A. Buhr 13 %% Last Modified On : Mon Nov 27 18:09:59 201714 %% Update Count : 3 14313 %% Last Modified On : Thu Jul 26 17:29:05 2018 14 %% Update Count : 3366 15 15 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 16 16 … … 40 40 \usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref} 41 41 \usepackage{breakurl} 42 \renewcommand{\UrlFont}{\small\sf}43 42 44 43 \usepackage[pagewise]{lineno} … … 73 72 74 73 % Names used in the document. 75 \newcommand{\Version}{\input{ ../../version}}74 \newcommand{\Version}{\input{build/version}} 76 75 \newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}} 77 76 \newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}} … … 147 146 \CFA adds many modern programming-language features that directly lead to increased \emph{\Index{safety}} and \emph{\Index{productivity}}, while maintaining interoperability with existing C programs and achieving similar performance. 148 147 Like C, \CFA is a statically typed, procedural (non-\Index{object-oriented}) language with a low-overhead runtime, meaning there is no global \Index{garbage-collection}, but \Index{regional garbage-collection}\index{garbage-collection!regional} is possible. 149 The primary new features include p arametric-polymorphic routines and types, exceptions, concurrency, and modules.148 The primary new features include polymorphic routines and types, exceptions, concurrency, and modules. 150 149 151 150 One of the main design philosophies of \CFA is to ``\Index{describe not prescribe}'', which means \CFA tries to provide a pathway from low-level C programming to high-level \CFA programming, but it does not force programmers to ``do the right thing''. … … 156 155 As well, new programs can be written in \CFA using a combination of C and \CFA features. 157 156 158 \Index*[C++]{\CC{}} had a similar goal 30 years ago, allowing object-oriented programming to be incrementally added to C.159 However, \CC currently has the disadvantages of a strong object-oriented bias, multiple legacy design-choices that cannot be updated, and active divergence of the language model from C, all of which requiressignificant effort and training to incrementally add \CC to a C-based project.157 \Index*[C++]{\CC{}}~\cite{c++:v1} had a similar goal 30 years ago, allowing object-oriented programming to be incrementally added to C. 158 However, \CC currently has the disadvantages of a strong object-oriented bias, multiple legacy design-choices that cannot be updated, and active divergence of the language model from C, requiring significant effort and training to incrementally add \CC to a C-based project. 160 159 In contrast, \CFA has 30 years of hindsight and a clean starting point. 161 160 162 161 Like \Index*[C++]{\CC{}}, there may be both an old and new ways to achieve the same effect. 163 For example, the following programs compare the \CFA, C, and \CC I/O mechanisms, where the programs output the same result.164 \begin{ quote2}162 For example, the following programs compare the C, \CFA, and \CC I/O mechanisms, where the programs output the same result. 163 \begin{center} 165 164 \begin{tabular}{@{}l@{\hspace{1.5em}}l@{\hspace{1.5em}}l@{}} 166 165 \multicolumn{1}{c@{\hspace{1.5em}}}{\textbf{C}} & \multicolumn{1}{c}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{\CC}} \\ … … 192 191 \end{cfa} 193 192 \end{tabular} 194 \end{ quote2}193 \end{center} 195 194 While the \CFA I/O looks similar to the \Index*[C++]{\CC{}} output style, there are important differences, such as automatic spacing between variables as in \Index*{Python} (see~\VRef{s:IOLibrary}). 196 195 … … 198 197 199 198 This document is a programmer reference-manual for the \CFA programming language. 200 The manual covers the core features of the language and runtime-system, with simple examples illustrating syntax and semantics of each feature.199 The manual covers the core features of the language and runtime-system, with simple examples illustrating syntax and semantics of features. 201 200 The manual does not teach programming, \ie how to combine the new constructs to build complex programs. 202 A reader should alreadyhave an intermediate knowledge of control flow, data structures, and concurrency issues to understand the ideas presented, as well as some experience programming in C/\CC.201 The reader must have an intermediate knowledge of control flow, data structures, and concurrency issues to understand the ideas presented, as well as some experience programming in C/\CC. 203 202 Implementers should refer to the \CFA Programming Language Specification for details about the language syntax and semantics. 204 203 Changes to the syntax and additional features are expected to be included in later revisions. … … 207 206 \section{Why fix C?} 208 207 209 The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from commercial operating-systems (especially UNIX systems) to hobby projects.208 The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from hobby projects to commercial operating-systems. 210 209 This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more. 211 210 Even with all its problems, C continues to be popular because it allows writing software at virtually any level in a computer system without restriction. 212 211 For system programming, where direct access to hardware, storage management, and real-time issues are a requirement, C is usually the only language of choice. 213 The TIOBE index~\cite{TIOBE} for March 2016 showed the following programming-language popularity: \Index*{Java} 20.5\%, C 14.5\%, \Index*[C++]{\CC{}} 6.7\%, \Csharp 4.3\%, \Index*{Python} 4.3\%, where the next 50 languages are less than 3\% eachwith a long tail.214 As well, for 30 years, C has been the number 1 and 2 most popular programming language:212 The TIOBE index~\cite{TIOBE} for July 2018 ranks the top 5 most \emph{popular} programming languages as: \Index*{Java} 16\%, C 14\%, \Index*[C++]{\CC{}} 7.5\%, Python 6\%, Visual Basic 4\% = 47.5\%, where the next 50 languages are less than 4\% each, with a long tail. 213 The top 3 rankings over the past 30 years are: 215 214 \begin{center} 216 \setlength{\tabcolsep}{1.5ex} 217 \begin{tabular}{@{}r|c|c|c|c|c|c|c@{}} 218 Ranking & 2016 & 2011 & 2006 & 2001 & 1996 & 1991 & 1986 \\ 219 \hline 220 Java & 1 & 1 & 1 & 3 & 29 & - & - \\ 221 \hline 222 \R{C} & \R{2} & \R{2} & \R{2} & \R{1} & \R{1} & \R{1} & \R{1} \\ 223 \hline 224 \CC & 3 & 3 & 3 & 2 & 2 & 2 & 7 \\ 215 \setlength{\tabcolsep}{10pt} 216 \begin{tabular}{@{}rccccccc@{}} 217 & 2018 & 2013 & 2008 & 2003 & 1998 & 1993 & 1988 \\ \hline 218 Java & 1 & 2 & 1 & 1 & 16 & - & - \\ 219 \R{C} & \R{2} & \R{1} & \R{2} & \R{2} & \R{1} & \R{1} & \R{1} \\ 220 \CC & 3 & 4 & 3 & 3 & 2 & 2 & 5 \\ 225 221 \end{tabular} 226 222 \end{center} 227 223 Hence, C is still an extremely important programming language, with double the usage of \Index*[C++]{\CC{}}; in many cases, \CC is often used solely as a better C. 228 224 Love it or hate it, C has been an important and influential part of computer science for 40 years and its appeal is not diminishing. 229 Unfortunately, C has many problems and omissions that make it an unacceptable programming language for modern needs.225 Nevertheless, C has many problems and omissions that make it an unacceptable programming language for modern needs. 230 226 231 227 As stated, the goal of the \CFA project is to engineer modern language-features into C in an evolutionary rather than revolutionary way. … … 237 233 These languages have different syntax and semantics from C, do not interoperate directly with C, and are not systems languages because of restrictive memory-management or garbage collection. 238 234 As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten. 239 These costs can be prohibitive for many companies with a large software-base in C/\CC, and a significant number of programmers require retraining to the new programming language. 240 241 The result of this project is a language that is largely backwards compatible with \Index*[C11]{\Celeven{}}~\cite{C11}, but fixes many of the well known C problems while containing modern language-features. 242 Without significant extension to the C programming language, it is becoming unable to cope with the needs of modern programming problems and programmers; 235 These costs can be prohibitive for many companies with a large software-base in C/\CC, and a significant number of programmers require retraining in the new programming language. 236 237 The result of this project is a language that is largely backwards compatible with \Index*[C11]{\Celeven{}}~\cite{C11}, but fixes many of the well known C problems while adding modern language-features. 238 To achieve these goals required a significant engineering exercise, where we had to ``think inside the existing C box''. 239 Without these significant extension to C, it is unable to cope with the needs of modern programming problems and programmers; 243 240 as a result, it will fade into disuse. 244 241 Considering the large body of existing C code and programmers, there is significant impetus to ensure C is transformed into a modern programming language. … … 256 253 \begin{lstlisting} 257 254 ®forall( otype T )® T identity( T val ) { return val; } 258 int forty_two = identity( 42 ); §\C{// T is bound to int, forty\_two == 42}§255 int forty_two = identity( 42 ); §\C{// T is bound to int, forty\_two == 42}§ 259 256 \end{lstlisting} 260 257 % extending the C type system with parametric polymorphism and overloading, as opposed to the \Index*[C++]{\CC{}} approach of object-oriented extensions. … … 275 272 276 273 \begin{comment} 277 A simple example is leveraging the existing type-unsafe (©void *©) C ©bsearch© to binary search a sorted floating -pointarray:274 A simple example is leveraging the existing type-unsafe (©void *©) C ©bsearch© to binary search a sorted floating array: 278 275 \begin{lstlisting} 279 276 void * bsearch( const void * key, const void * base, size_t dim, size_t size, … … 283 280 *(double *)t2 < *(double *)t1 ? 1 : 0; } 284 281 285 double key = 5.0, vals[10] = { /* 10 sorted floating -pointvalues */ };286 double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp ); $\C{// search sorted array}$282 double key = 5.0, vals[10] = { /* 10 sorted floating values */ }; 283 double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp ); §\C{// search sorted array}§ 287 284 \end{lstlisting} 288 285 which can be augmented simply with a polymorphic, type-safe, \CFA-overloaded wrappers: … … 293 290 294 291 forall( otype T | { int ?<?( T, T ); } ) unsigned int bsearch( T key, const T * arr, size_t size ) { 295 T * result = bsearch( key, arr, size ); $\C{// call first version}$296 return result ? result - arr : size; } $\C{// pointer subtraction includes sizeof(T)}$297 298 double * val = bsearch( 5.0, vals, 10 ); $\C{// selection based on return type}$292 T * result = bsearch( key, arr, size ); §\C{// call first version}§ 293 return result ? result - arr : size; } §\C{// pointer subtraction includes sizeof(T)}§ 294 295 double * val = bsearch( 5.0, vals, 10 ); §\C{// selection based on return type}§ 299 296 int posn = bsearch( 5.0, vals, 10 ); 300 297 \end{lstlisting} … … 308 305 \begin{lstlisting} 309 306 forall( dtype T | sized(T) ) T * malloc( void ) { return (T *)malloc( sizeof(T) ); } 310 int * ip = malloc(); §\C{// select type and size from left-hand side}§307 int * ip = malloc(); §\C{// select type and size from left-hand side}§ 311 308 double * dp = malloc(); 312 309 struct S {...} * sp = malloc(); … … 319 316 Whereas, \CFA wraps each of these routines into ones with the overloaded name ©abs©: 320 317 \begin{cfa} 321 char abs( char );322 ®extern "C" {® int abs( int ); ®}®§\C{// use default C routine for int}§323 long int abs( long int );324 long long int abs( long long int );325 float abs( float );326 double abs( double );327 long double abs( long double );328 float _Complex abs( float _Complex );329 double _Complex abs( double _Complex );330 long double _Complex abs( long double _Complex );318 char ®abs®( char ); 319 extern "C" { int ®abs®( int ); } §\C{// use default C routine for int}§ 320 long int ®abs®( long int ); 321 long long int ®abs®( long long int ); 322 float ®abs®( float ); 323 double ®abs®( double ); 324 long double ®abs®( long double ); 325 float _Complex ®abs®( float _Complex ); 326 double _Complex ®abs®( double _Complex ); 327 long double _Complex ®abs®( long double _Complex ); 331 328 \end{cfa} 332 329 The problem is the name clash between the library routine ©abs© and the \CFA names ©abs©. 333 330 Hence, names appearing in an ©extern "C"© block have \newterm*{C linkage}. 334 331 Then overloading polymorphism uses a mechanism called \newterm{name mangling}\index{mangling!name} to create unique names that are different from C names, which are not mangled. 335 Hence, there is the same need as in \CC, to know if a name is a C or \CFA name, so it can be correctly formed.336 There is no way around this problem, other than C's approach of creating unique names for each pairing of operation and type .332 Hence, there is the same need, as in \CC, to know if a name is a C or \CFA name, so it can be correctly formed. 333 There is no way around this problem, other than C's approach of creating unique names for each pairing of operation and types. 337 334 338 335 This example strongly illustrates a core idea in \CFA: \emph{the \Index{power of a name}}. … … 351 348 \begin{description} 352 349 \item 353 \Indexc{-std=gnu 99}\index{compilation option!-std=gnu99@{©-std=gnu99©}}354 The 1999C standard plus GNU extensions.355 \item 356 \Indexc[deletekeywords=inline]{-fgnu89-inline}\index{compilation option!-fgnu89-inline@{\lstinline[deletekeywords=inline] $-fgnu89-inline$}}357 Use the traditional GNU semantics for inline routines in C 99mode, which allows inline routines in header files.350 \Indexc{-std=gnu11}\index{compilation option!-std=gnu11@{©-std=gnu11©}} 351 The 2011 C standard plus GNU extensions. 352 \item 353 \Indexc[deletekeywords=inline]{-fgnu89-inline}\index{compilation option!-fgnu89-inline@{\lstinline[deletekeywords=inline]@-fgnu89-inline@}} 354 Use the traditional GNU semantics for inline routines in C11 mode, which allows inline routines in header files. 358 355 \end{description} 359 356 The following new \CFA options are available: … … 428 425 \begin{cfa} 429 426 #ifndef __CFORALL__ 430 #include <stdio.h>§\indexc{stdio.h}§ §\C{// C header file}§427 #include <stdio.h>§\indexc{stdio.h}§ §\C{// C header file}§ 431 428 #else 432 #include <fstream>§\indexc{fstream}§ §\C{// \CFA header file}§429 #include <fstream>§\indexc{fstream}§ §\C{// \CFA header file}§ 433 430 #endif 434 431 \end{cfa} 435 which conditionally includes the correct header file, if the program is compiled using \Indexc{gcc} or \Indexc{cfa}. 432 which conditionally includes the correct header file, if the program is compiled using \Indexc{gcc} or \Indexc{cfa}. 433 434 435 \section{Backquote Identifiers} 436 \label{s:BackquoteIdentifiers} 437 438 \CFA introduces several new keywords (see \VRef{s:CFAKeywords}) that can clash with existing C variable-names in legacy code. 439 Keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism: 440 \begin{cfa} 441 int ®`®otype®`® = 3; §\C{// make keyword an identifier}§ 442 double ®`®forall®`® = 3.5; 443 \end{cfa} 444 445 Existing C programs with keyword clashes can be converted by enclosing keyword identifiers in backquotes, and eventually the identifier name can be changed to a non-keyword name. 446 \VRef[Figure]{f:HeaderFileInterposition} shows how clashes in existing C header-files (see~\VRef{s:StandardHeaders}) can be handled using preprocessor \newterm{interposition}: ©#include_next© and ©-I filename©. 447 Several common C header-files with keyword clashes are fixed in the standard \CFA header-library, so there is a seamless programming-experience. 448 449 \begin{figure} 450 \begin{cfa} 451 // include file uses the CFA keyword "with". 452 #if ! defined( with ) §\C{// nesting ?}§ 453 #define with ®`®with®`® §\C{// make keyword an identifier}§ 454 #define __CFA_BFD_H__ 455 #endif 456 457 ®#include_next <bfdlink.h> §\C{// must have internal check for multiple expansion}§ 458 ® 459 #if defined( with ) && defined( __CFA_BFD_H__ ) §\C{// reset only if set}§ 460 #undef with 461 #undef __CFA_BFD_H__ 462 #endif 463 \end{cfa} 464 \caption{Header-File Interposition} 465 \label{f:HeaderFileInterposition} 466 \end{figure} 436 467 437 468 … … 440 471 Numeric constants are extended to allow \Index{underscore}s\index{constant!underscore}, \eg: 441 472 \begin{cfa} 442 2®_®147®_®483®_®648; §\C{// decimal constant}§443 56®_®ul; §\C{// decimal unsigned long constant}§444 0®_®377; §\C{// octal constant}§445 0x®_®ff®_®ff; §\C{// hexadecimal constant}§446 0x®_®ef3d®_®aa5c; §\C{// hexadecimal constant}§447 3.141®_®592®_®654; §\C{// floating pointconstant}§448 10®_®e®_®+1®_®00; §\C{// floating pointconstant}§449 0x®_®ff®_®ff®_®p®_®3; §\C{// hexadecimal floating point}§450 0x®_®1.ffff®_®ffff®_®p®_®128®_®l; §\C{// hexadecimal floating pointlong constant}§473 2®_®147®_®483®_®648; §\C{// decimal constant}§ 474 56®_®ul; §\C{// decimal unsigned long constant}§ 475 0®_®377; §\C{// octal constant}§ 476 0x®_®ff®_®ff; §\C{// hexadecimal constant}§ 477 0x®_®ef3d®_®aa5c; §\C{// hexadecimal constant}§ 478 3.141®_®592®_®654; §\C{// floating constant}§ 479 10®_®e®_®+1®_®00; §\C{// floating constant}§ 480 0x®_®ff®_®ff®_®p®_®3; §\C{// hexadecimal floating}§ 481 0x®_®1.ffff®_®ffff®_®p®_®128®_®l; §\C{// hexadecimal floating long constant}§ 451 482 L®_®§"\texttt{\textbackslash{x}}§®_®§\texttt{ff}§®_®§\texttt{ee}"§; §\C{// wide character constant}§ 452 483 \end{cfa} … … 470 501 471 502 472 \section{Backquote Identifiers} 473 \label{s:BackquoteIdentifiers} 474 475 \CFA introduces several new keywords (see \VRef{s:CFAKeywords}) that can clash with existing C variable-names in legacy code. 476 Keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism: 477 \begin{cfa} 478 int ®`®otype®`® = 3; §\C{// make keyword an identifier}§ 479 double ®`®forall®`® = 3.5; 480 \end{cfa} 481 482 Existing C programs with keyword clashes can be converted by enclosing keyword identifiers in backquotes, and eventually the identifier name can be changed to a non-keyword name. 483 \VRef[Figure]{f:HeaderFileInterposition} shows how clashes in existing C header-files (see~\VRef{s:StandardHeaders}) can be handled using preprocessor \newterm{interposition}: ©#include_next© and ©-I filename©. 484 Several common C header-files with keyword clashes are fixed in the standard \CFA header-library, so there is a seamless programming-experience. 485 486 \begin{figure} 487 \begin{cfa} 488 // include file uses the CFA keyword "with". 489 #if ! defined( with ) §\C{// nesting ?}§ 490 #define with ®`®with®`® §\C{// make keyword an identifier}§ 491 #define __CFA_BFD_H__ 492 #endif 493 494 ®#include_next <bfdlink.h> §\C{// must have internal check for multiple expansion}§ 495 ® 496 #if defined( with ) && defined( __CFA_BFD_H__ ) §\C{// reset only if set}§ 497 #undef with 498 #undef __CFA_BFD_H__ 499 #endif 500 \end{cfa} 501 \caption{Header-File Interposition} 502 \label{f:HeaderFileInterposition} 503 \end{figure} 504 505 506 \section{\texorpdfstring{Labelled \LstKeywordStyle{continue} / \LstKeywordStyle{break}}{Labelled continue / break}} 503 \section{Exponentiation Operator} 504 505 C, \CC, and Java (and many other programming languages) have no exponentiation operator\index{exponentiation!operator}\index{operator!exponentiation}, \ie $x^y$, and instead use a routine, like \Indexc{pow}, to perform the exponentiation operation. 506 \CFA extends the basic operators with the exponentiation operator ©?\?©\index{?\\?@\lstinline@?\?@} and ©?\=?©\index{?\\=?@\lstinline@?\=?@}, as in, ©x \ y© and ©x \= y©, which means $x^y$ and $x \leftarrow x^y$. 507 The priority of the exponentiation operator is between the cast and multiplicative operators, so that ©w * (int)x \ (int)y * z© is parenthesized as ©((w * (((int)x) \ ((int)y))) * z)©. 508 509 As for \Index{division}, there are exponentiation operators for integral and floating types, including the builtin \Index{complex} types. 510 Unsigned integral exponentiation\index{exponentiation!unsigned integral} is performed with repeated multiplication\footnote{The multiplication computation is $O(\log y)$.} (or shifting if the base is 2). 511 Signed integral exponentiation\index{exponentiation!signed integral} is performed with repeated multiplication (or shifting if the base is 2), but yields a floating result because $x^{-y}=1/x^y$. 512 Hence, it is important to designate exponent integral-constants as unsigned or signed: ©3 \ 3u© return an integral result, while ©3 \ 3© returns a floating result. 513 Floating exponentiation\index{exponentiation!floating} is performed using \Index{logarithm}s\index{exponentiation!logarithm}, so the base cannot be negative. 514 \begin{cfa} 515 sout | 2 ®\® 8u | 4 ®\® 3u | -4 ®\® 3u | 4 ®\® -3 | -4 ®\® -3 | 4.0 ®\® 2.1 | (1.0f+2.0fi) ®\® (3.0f+2.0fi) | endl; 516 256 64 -64 0.015625 -0.015625 18.3791736799526 0.264715-1.1922i 517 \end{cfa} 518 Parenthesis are necessary for the complex constants or the expression is parsed as ©1.0f+(2.0fi \ 3.0f)+2.0fi©. 519 The exponentiation operator is available for all the basic types, but for user-defined types, only the integral-computation versions are available. 520 For returning an integral value, the user type ©T© must define multiplication, ©*©, and one, ©1©; 521 for returning a floating value, an additional divide of type ©T© into a ©double© returning a ©double© (©double ?/?( double, T )©) is necessary for negative exponents. 522 523 524 \section{Control Structures} 525 526 \CFA identifies inconsistent, problematic, and missing control structures in C, and extends, modifies, and adds control structures to increase functionality and safety. 527 528 529 %\subsection{\texorpdfstring{\protect\lstinline@if@ Statement}{if Statement}} 530 \subsection{\texorpdfstring{\LstKeywordStyle{if} Statement}{if Statement}} 531 532 The ©if© expression allows declarations, similar to ©for© declaration expression: 533 \begin{cfa} 534 if ( int x = f() ) ... §\C{// x != 0}§ 535 if ( int x = f(), y = g() ) ... §\C{// x != 0 \&\& y != 0}§ 536 if ( int x = f(), y = g(); ®x < y® ) ... §\C{// relational expression}§ 537 \end{cfa} 538 Unless a relational expression is specified, each variable is compared not equal to 0, which is the standard semantics for the ©if© expression, and the results are combined using the logical ©&&© operator.\footnote{\CC only provides a single declaration always compared not equal to 0.} 539 The scope of the declaration(s) is local to the @if@ statement but exist within both the ``then'' and ``else'' clauses. 540 541 542 %\section{\texorpdfstring{\protect\lstinline@switch@ Statement}{switch Statement}} 543 \subsection{\texorpdfstring{\LstKeywordStyle{switch} Statement}{switch Statement}} 544 545 C allows a number of questionable forms for the ©switch© statement: 546 \begin{enumerate} 547 \item 548 By default, the end of a ©case© clause\footnote{ 549 In this section, the term \emph{case clause} refers to either a ©case© or ©default© clause.} 550 \emph{falls through} to the next ©case© clause in the ©switch© statement; 551 to exit a ©switch© statement from a ©case© clause requires explicitly terminating the clause with a transfer statement, most commonly ©break©: 552 \begin{cfa} 553 switch ( i ) { 554 case 1: 555 ... 556 // fall-through 557 case 2: 558 ... 559 break; // exit switch statement 560 } 561 \end{cfa} 562 The ability to fall-through to the next clause \emph{is} a useful form of control flow, specifically when a sequence of case actions compound: 563 \begin{cquote} 564 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 565 \begin{cfa} 566 switch ( argc ) { 567 case 3: 568 // open output file 569 // fall-through 570 case 2: 571 // open input file 572 break; // exit switch statement 573 default: 574 // usage message 575 } 576 \end{cfa} 577 & 578 \begin{cfa} 579 580 if ( argc == 3 ) { 581 // open output file 582 ®// open input file 583 ®} else if ( argc == 2 ) { 584 ®// open input file (duplicate) 585 586 ®} else { 587 // usage message 588 } 589 \end{cfa} 590 \end{tabular} 591 \end{cquote} 592 In this example, case 2 is always done if case 3 is done. 593 This control flow is difficult to simulate with if statements or a ©switch© statement without fall-through as code must be duplicated or placed in a separate routine. 594 C also uses fall-through to handle multiple case-values resulting in the same action: 595 \begin{cfa} 596 switch ( i ) { 597 ®case 1: case 3: case 5:® // odd values 598 // odd action 599 break; 600 ®case 2: case 4: case 6:® // even values 601 // even action 602 break; 603 } 604 \end{cfa} 605 However, this situation is handled in other languages without fall-through by allowing a list of case values. 606 While fall-through itself is not a problem, the problem occurs when fall-through is the default, as this semantics is unintuitive to many programmers and is different from virtually all other programming languages with a ©switch© statement. 607 Hence, default fall-through semantics results in a large number of programming errors as programmers often \emph{forget} the ©break© statement at the end of a ©case© clause, resulting in inadvertent fall-through. 608 609 \item 610 It is possible to place ©case© clauses on statements nested \emph{within} the body of the ©switch© statement: 611 \begin{cfa} 612 switch ( i ) { 613 case 0: 614 if ( j < k ) { 615 ... 616 ®case 1:® // transfer into "if" statement 617 ... 618 } // if 619 case 2: 620 while ( j < 5 ) { 621 ... 622 ®case 3:® // transfer into "while" statement 623 ... 624 } // while 625 } // switch 626 \end{cfa} 627 The problem with this usage is branching into control structures, which is known to cause both comprehension and technical difficulties. 628 The comprehension problem occurs from the inability to determine how control reaches a particular point due to the number of branches leading to it. 629 The technical problem results from the inability to ensure declaration and initialization of variables when blocks are not entered at the beginning. 630 There are no positive arguments for this kind of control flow, and therefore, there is a strong impetus to eliminate it. 631 Nevertheless, C does have an idiom where this capability is used, known as ``\Index*{Duff's device}''~\cite{Duff83}: 632 \begin{cfa} 633 register int n = (count + 7) / 8; 634 switch ( count % 8 ) { 635 case 0: do{ *to = *from++; 636 case 7: *to = *from++; 637 case 6: *to = *from++; 638 case 5: *to = *from++; 639 case 4: *to = *from++; 640 case 3: *to = *from++; 641 case 2: *to = *from++; 642 case 1: *to = *from++; 643 } while ( --n > 0 ); 644 } 645 \end{cfa} 646 which unrolls a loop N times (N = 8 above) and uses the ©switch© statement to deal with any iterations not a multiple of N. 647 While efficient, this sort of special purpose usage is questionable: 648 \begin{quote} 649 Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this 650 discovery.~\cite{Duff83} 651 \end{quote} 652 \item 653 It is possible to place the ©default© clause anywhere in the list of labelled clauses for a ©switch© statement, rather than only at the end. 654 Virtually all programming languages with a ©switch© statement require the ©default© clause to appear last in the case-clause list. 655 The logic for this semantics is that after checking all the ©case© clauses without success, the ©default© clause is selected; 656 hence, physically placing the ©default© clause at the end of the ©case© clause list matches with this semantics. 657 This physical placement can be compared to the physical placement of an ©else© clause at the end of a series of connected ©if©/©else© statements. 658 659 \item 660 It is possible to place unreachable code at the start of a ©switch© statement, as in: 661 \begin{cfa} 662 switch ( x ) { 663 ®int y = 1;® §\C{// unreachable initialization}§ 664 ®x = 7;® §\C{// unreachable code without label/branch}§ 665 case 0: ... 666 ... 667 ®int z = 0;® §\C{// unreachable initialization, cannot appear after case}§ 668 z = 2; 669 case 1: 670 ®x = z;® §\C{// without fall through, z is uninitialized}§ 671 } 672 \end{cfa} 673 While the declaration of the local variable ©y© is useful with a scope across all ©case© clauses, the initialization for such a variable is defined to never be executed because control always transfers over it. 674 Furthermore, any statements before the first ©case© clause can only be executed if labelled and transferred to using a ©goto©, either from outside or inside of the ©switch©, both of which are problematic. 675 As well, the declaration of ©z© cannot occur after the ©case© because a label can only be attached to a statement, and without a fall through to case 3, ©z© is uninitialized. 676 The key observation is that the ©switch© statement branches into control structure, \ie there are multiple entry points into its statement body. 677 \end{enumerate} 678 679 Before discussing potential language changes to deal with these problems, it is worth observing that in a typical C program: 680 \begin{itemize} 681 \item 682 the number of ©switch© statements is small, 683 \item 684 most ©switch© statements are well formed (\ie no \Index*{Duff's device}), 685 \item 686 the ©default© clause is usually written as the last case-clause, 687 \item 688 and there is only a medium amount of fall-through from one ©case© clause to the next, and most of these result from a list of case values executing common code, rather than a sequence of case actions that compound. 689 \end{itemize} 690 These observations put into perspective the \CFA changes to the ©switch©. 691 \begin{enumerate} 692 \item 693 Eliminating default fall-through has the greatest potential for affecting existing code. 694 However, even if fall-through is removed, most ©switch© statements would continue to work because of the explicit transfers already present at the end of each ©case© clause, the common placement of the ©default© clause at the end of the case list, and the most common use of fall-through, \ie a list of ©case© clauses executing common code, \eg: 695 \begin{cfa} 696 case 1: case 2: case 3: ... 697 \end{cfa} 698 still works. 699 Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments. 700 Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called ©choose©, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword ©fallthrough©/©fallthru©, \eg: 701 \begin{cfa} 702 ®choose® ( i ) { 703 case 1: case 2: case 3: 704 ... 705 ®// implicit end of switch (break) 706 ®case 5: 707 ... 708 ®fallthru®; §\C{// explicit fall through}§ 709 case 7: 710 ... 711 ®break® §\C{// explicit end of switch (redundant)}§ 712 default: 713 j = 3; 714 } 715 \end{cfa} 716 Like the ©switch© statement, the ©choose© statement retains the fall-through semantics for a list of ©case© clauses; 717 An implicit ©break© is applied only at the end of the \emph{statements} following a ©case© clause. 718 An explicit ©fallthru© is retained because it is a C-idiom most C programmers expect, and its absence might discourage programmers from using the ©choose© statement. 719 As well, allowing an explicit ©break© from the ©choose© is a carry over from the ©switch© statement, and expected by C programmers. 720 \item 721 \Index*{Duff's device} is eliminated from both ©switch© and ©choose© statements, and only invalidates a small amount of very questionable code. 722 Hence, the ©case© clause must appear at the same nesting level as the ©switch©/©choose© body, as is done in most other programming languages with ©switch© statements. 723 \item 724 The issue of ©default© at locations other than at the end of the cause clause can be solved by using good programming style, and there are a few reasonable situations involving fall-through where the ©default© clause needs to appear is locations other than at the end. 725 Therefore, no change is made for this issue. 726 \item 727 Dealing with unreachable code in a ©switch©/©choose© body is solved by restricting declarations and associated initialization to the start of statement body, which is executed \emph{before} the transfer to the appropriate ©case© clause\footnote{ 728 Essentially, these declarations are hoisted before the ©switch©/©choose© statement and both declarations and statement are surrounded by a compound statement.} and precluding statements before the first ©case© clause. 729 Further declarations at the same nesting level as the statement body are disallowed to ensure every transfer into the body is sound. 730 \begin{cfa} 731 switch ( x ) { 732 ®int i = 0;® §\C{// allowed only at start}§ 733 case 0: 734 ... 735 ®int j = 0;® §\C{// disallowed}§ 736 case 1: 737 { 738 ®int k = 0;® §\C{// allowed at different nesting levels}§ 739 ... 740 ®case 2:® §\C{// disallow case in nested statements}§ 741 } 742 ... 743 } 744 \end{cfa} 745 \end{enumerate} 746 747 748 %\section{\texorpdfstring{\protect\lstinline@case@ Clause}{case Clause}} 749 \subsection{\texorpdfstring{\LstKeywordStyle{case} Statement}{case Statement}} 750 751 C restricts the ©case© clause of a ©switch© statement to a single value. 752 For multiple ©case© clauses associated with the same statement, it is necessary to have multiple ©case© clauses rather than multiple values. 753 Requiring a ©case© clause for each value does not seem to be in the spirit of brevity normally associated with C. 754 Therefore, the ©case© clause is extended with a list of values, as in: 755 \begin{cquote} 756 \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} 757 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ 758 \begin{cfa} 759 switch ( i ) { 760 case ®1, 3, 5®: 761 ... 762 case ®2, 4, 6®: 763 ... 764 } 765 \end{cfa} 766 & 767 \begin{cfa} 768 switch ( i ) { 769 case 1: case 3 : case 5: 770 ... 771 case 2: case 4 : case 6: 772 ... 773 } 774 \end{cfa} 775 & 776 \begin{cfa} 777 778 // odd values 779 780 // even values 781 782 783 \end{cfa} 784 \end{tabular} 785 \end{cquote} 786 In addition, subranges are allowed to specify case values.\footnote{ 787 gcc has the same mechanism but awkward syntax, \lstinline@2 ...42@, because a space is required after a number, otherwise the period is a decimal point.} 788 \begin{cfa} 789 switch ( i ) { 790 case ®1~5:® §\C{// 1, 2, 3, 4, 5}§ 791 ... 792 case ®10~15:® §\C{// 10, 11, 12, 13, 14, 15}§ 793 ... 794 } 795 \end{cfa} 796 Lists of subranges are also allowed. 797 \begin{cfa} 798 case ®1~5, 12~21, 35~42®: 799 \end{cfa} 800 801 802 %\subsection{\texorpdfstring{Labelled \protect\lstinline@continue@ / \protect\lstinline@break@}{Labelled continue / break}} 803 \subsection{\texorpdfstring{Labelled \LstKeywordStyle{continue} / \LstKeywordStyle{break} Statement}{Labelled continue / break Statement}} 507 804 508 805 While C provides ©continue© and ©break© statements for altering control flow, both are restricted to one level of nesting for a particular control structure. 509 806 Unfortunately, this restriction forces programmers to use \Indexc{goto} to achieve the equivalent control-flow for more than one level of nesting. 510 To prevent having to switch to the ©goto©, \CFA extends the \Indexc{continue}\index{continue@\lstinline $continue$!labelled}\index{labelled!continue@©continue©} and \Indexc{break}\index{break@\lstinline $break$!labelled}\index{labelled!break@©break©} with a target label to support static multi-level exit\index{multi-level exit}\index{static multi-level exit}~\cite{Buhr85}, as in Java.807 To prevent having to switch to the ©goto©, \CFA extends the \Indexc{continue}\index{continue@\lstinline@continue@!labelled}\index{labelled!continue@©continue©} and \Indexc{break}\index{break@\lstinline@break@!labelled}\index{labelled!break@©break©} with a target label to support static multi-level exit\index{multi-level exit}\index{static multi-level exit}~\cite{Buhr85}, as in Java. 511 808 For both ©continue© and ©break©, the target label must be directly associated with a ©for©, ©while© or ©do© statement; 512 809 for ©break©, the target label can also be associated with a ©switch©, ©if© or compound (©{}©) statement. … … 593 890 \end{figure} 594 891 595 Both labelled ©continue© and ©break© are a ©goto©\index{goto@\lstinline $goto$!restricted} restricted in the following ways:892 Both labelled ©continue© and ©break© are a ©goto©\index{goto@\lstinline@goto@!restricted} restricted in the following ways: 596 893 \begin{itemize} 597 894 \item … … 606 903 With ©goto©, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader. 607 904 Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs. 608 The implicit targets of the current ©continue© and ©break©, \ie the closest enclosing loop or ©switch©, change as certain constructs are added or removed. 609 610 611 \section{\texorpdfstring{\LstKeywordStyle{switch} Statement}{switch Statement}} 612 613 C allows a number of questionable forms for the ©switch© statement: 614 \begin{enumerate} 615 \item 616 By default, the end of a ©case© clause\footnote{ 617 In this section, the term \emph{case clause} refers to either a ©case© or ©default© clause.} 618 \emph{falls through} to the next ©case© clause in the ©switch© statement; 619 to exit a ©switch© statement from a ©case© clause requires explicitly terminating the clause with a transfer statement, most commonly ©break©: 620 \begin{cfa} 621 switch ( i ) { 622 case 1: 623 ... 624 // fall-through 625 case 2: 626 ... 627 break; // exit switch statement 628 } 629 \end{cfa} 630 The ability to fall-through to the next clause \emph{is} a useful form of control flow, specifically when a sequence of case actions compound: 631 \begin{quote2} 632 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 633 \begin{cfa} 634 switch ( argc ) { 635 case 3: 636 // open output file 637 // fall-through 638 case 2: 639 // open input file 640 break; // exit switch statement 641 default: 642 // usage message 643 } 644 \end{cfa} 645 & 646 \begin{cfa} 647 648 if ( argc == 3 ) { 649 // open output file 650 ®// open input file 651 ®} else if ( argc == 2 ) { 652 ®// open input file (duplicate) 653 654 ®} else { 655 // usage message 656 } 657 \end{cfa} 658 \end{tabular} 659 \end{quote2} 660 In this example, case 2 is always done if case 3 is done. 661 This control flow is difficult to simulate with if statements or a ©switch© statement without fall-through as code must be duplicated or placed in a separate routine. 662 C also uses fall-through to handle multiple case-values resulting in the same action: 663 \begin{cfa} 664 switch ( i ) { 665 ®case 1: case 3: case 5:® // odd values 666 // odd action 667 break; 668 ®case 2: case 4: case 6:® // even values 669 // even action 670 break; 671 } 672 \end{cfa} 673 However, this situation is handled in other languages without fall-through by allowing a list of case values. 674 While fall-through itself is not a problem, the problem occurs when fall-through is the default, as this semantics is unintuitive to many programmers and is different from virtually all other programming languages with a ©switch© statement. 675 Hence, default fall-through semantics results in a large number of programming errors as programmers often \emph{forget} the ©break© statement at the end of a ©case© clause, resulting in inadvertent fall-through. 676 677 \item 678 It is possible to place ©case© clauses on statements nested \emph{within} the body of the ©switch© statement: 679 \begin{cfa} 680 switch ( i ) { 681 case 0: 682 if ( j < k ) { 683 ... 684 ®case 1:® // transfer into "if" statement 685 ... 686 } // if 687 case 2: 688 while ( j < 5 ) { 689 ... 690 ®case 3:® // transfer into "while" statement 691 ... 692 } // while 693 } // switch 694 \end{cfa} 695 The problem with this usage is branching into control structures, which is known to cause both comprehension and technical difficulties. 696 The comprehension problem occurs from the inability to determine how control reaches a particular point due to the number of branches leading to it. 697 The technical problem results from the inability to ensure declaration and initialization of variables when blocks are not entered at the beginning. 698 There are no positive arguments for this kind of control flow, and therefore, there is a strong impetus to eliminate it. 699 Nevertheless, C does have an idiom where this capability is used, known as ``\Index*{Duff's device}''~\cite{Duff83}: 700 \begin{cfa} 701 register int n = (count + 7) / 8; 702 switch ( count % 8 ) { 703 case 0: do{ *to = *from++; 704 case 7: *to = *from++; 705 case 6: *to = *from++; 706 case 5: *to = *from++; 707 case 4: *to = *from++; 708 case 3: *to = *from++; 709 case 2: *to = *from++; 710 case 1: *to = *from++; 711 } while ( --n > 0 ); 712 } 713 \end{cfa} 714 which unrolls a loop N times (N = 8 above) and uses the ©switch© statement to deal with any iterations not a multiple of N. 715 While efficient, this sort of special purpose usage is questionable: 716 \begin{quote} 717 Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this 718 discovery.~\cite{Duff83} 719 \end{quote} 720 \item 721 It is possible to place the ©default© clause anywhere in the list of labelled clauses for a ©switch© statement, rather than only at the end. 722 Virtually all programming languages with a ©switch© statement require the ©default© clause to appear last in the case-clause list. 723 The logic for this semantics is that after checking all the ©case© clauses without success, the ©default© clause is selected; 724 hence, physically placing the ©default© clause at the end of the ©case© clause list matches with this semantics. 725 This physical placement can be compared to the physical placement of an ©else© clause at the end of a series of connected ©if©/©else© statements. 726 727 \item 728 It is possible to place unreachable code at the start of a ©switch© statement, as in: 729 \begin{cfa} 730 switch ( x ) { 731 ®int y = 1;® §\C{// unreachable initialization}§ 732 ®x = 7;® §\C{// unreachable code without label/branch}§ 733 case 3: ... 734 ... 735 ®int z = 0;® §\C{// unreachable initialization, cannot appear after case}§ 736 z = 2; 737 case 3: 738 ®x = z;® §\C{// without fall through, z is uninitialized}§ 739 } 740 \end{cfa} 741 While the declaration of the local variable ©y© is useful with a scope across all ©case© clauses, the initialization for such a variable is defined to never be executed because control always transfers over it. 742 Furthermore, any statements before the first ©case© clause can only be executed if labelled and transferred to using a ©goto©, either from outside or inside of the ©switch©, both of which are problematic. 743 As well, the declaration of ©z© cannot occur after the ©case© because a label can only be attached to a statement, and without a fall through to case 3, ©z© is uninitialized. 744 The key observation is that the ©switch© statement branches into control structure, \ie there are multiple entry points into its statement body. 745 \end{enumerate} 746 747 Before discussing potential language changes to deal with these problems, it is worth observing that in a typical C program: 748 \begin{itemize} 749 \item 750 the number of ©switch© statements is small, 751 \item 752 most ©switch© statements are well formed (\ie no \Index*{Duff's device}), 753 \item 754 the ©default© clause is usually written as the last case-clause, 755 \item 756 and there is only a medium amount of fall-through from one ©case© clause to the next, and most of these result from a list of case values executing common code, rather than a sequence of case actions that compound. 757 \end{itemize} 758 These observations put into perspective the \CFA changes to the ©switch©. 759 \begin{enumerate} 760 \item 761 Eliminating default fall-through has the greatest potential for affecting existing code. 762 However, even if fall-through is removed, most ©switch© statements would continue to work because of the explicit transfers already present at the end of each ©case© clause, the common placement of the ©default© clause at the end of the case list, and the most common use of fall-through, \ie a list of ©case© clauses executing common code, \eg: 763 \begin{cfa} 764 case 1: case 2: case 3: ... 765 \end{cfa} 766 still works. 767 Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments. 768 Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called ©choose©, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword ©fallthrough©/©fallthru©, \eg: 769 \begin{cfa} 770 ®choose® ( i ) { 771 case 1: case 2: case 3: 772 ... 773 ®// implicit end of switch (break) 774 ®case 5: 775 ... 776 ®fallthru®; §\C{// explicit fall through}§ 777 case 7: 778 ... 779 ®break® §\C{// explicit end of switch (redundant)}§ 780 default: 781 j = 3; 782 } 783 \end{cfa} 784 Like the ©switch© statement, the ©choose© statement retains the fall-through semantics for a list of ©case© clauses; 785 An implicit ©break© is applied only at the end of the \emph{statements} following a ©case© clause. 786 An explicit ©fallthru© is retained because it is a C-idiom most C programmers expect, and its absence might discourage programmers from using the ©choose© statement. 787 As well, allowing an explicit ©break© from the ©choose© is a carry over from the ©switch© statement, and expected by C programmers. 788 \item 789 \Index*{Duff's device} is eliminated from both ©switch© and ©choose© statements, and only invalidates a small amount of very questionable code. 790 Hence, the ©case© clause must appear at the same nesting level as the ©switch©/©choose© body, as is done in most other programming languages with ©switch© statements. 791 \item 792 The issue of ©default© at locations other than at the end of the cause clause can be solved by using good programming style, and there are a few reasonable situations involving fall-through where the ©default© clause needs to appear is locations other than at the end. 793 Therefore, no change is made for this issue. 794 \item 795 Dealing with unreachable code in a ©switch©/©choose© body is solved by restricting declarations and associated initialization to the start of statement body, which is executed \emph{before} the transfer to the appropriate ©case© clause\footnote{ 796 Essentially, these declarations are hoisted before the ©switch©/©choose© statement and both declarations and statement are surrounded by a compound statement.} and precluding statements before the first ©case© clause. 797 Further declarations at the same nesting level as the statement body are disallowed to ensure every transfer into the body is sound. 798 \begin{cfa} 799 switch ( x ) { 800 ®int i = 0;® §\C{// allowed only at start}§ 801 case 0: 802 ... 803 ®int j = 0;® §\C{// disallowed}§ 804 case 1: 805 { 806 ®int k = 0;® §\C{// allowed at different nesting levels}§ 807 ... 808 ®case 2:® §\C{// disallow case in nested statements}§ 905 Otherwise, the implicit targets of the current ©continue© and ©break©, \ie the closest enclosing loop or ©switch©, change as certain constructs are added or removed. 906 907 908 %\section{\texorpdfstring{\protect\lstinline@with@ Statement}{with Statement}} 909 \section{\texorpdfstring{\LstKeywordStyle{with} Statement}{with Statement}} 910 \label{s:WithStatement} 911 912 Grouping heterogeneous data into \newterm{aggregate}s (structure/union) is a common programming practice, and an aggregate can be further organized into more complex structures, such as arrays and containers: 913 \begin{cfa} 914 struct S { §\C{// aggregate}§ 915 char c; §\C{// fields}§ 916 int i; 917 double d; 918 }; 919 S s, as[10]; 920 \end{cfa} 921 However, functions manipulating aggregates must repeat the aggregate name to access its containing fields: 922 \begin{cfa} 923 void f( S s ) { 924 ®s.®c; ®s.®i; ®s.®d; §\C{// access containing fields}§ 925 } 926 \end{cfa} 927 which extends to multiple levels of qualification for nested aggregates. 928 A similar situation occurs in object-oriented programming, \eg \CC: 929 \begin{C++} 930 struct S { 931 char c; §\C{// fields}§ 932 int i; 933 double d; 934 void f() { §\C{// implicit ``this'' aggregate}§ 935 ®this->®c; ®this->®i; ®this->®d; §\C{// access containing fields}§ 809 936 } 810 ... 811 } 812 \end{cfa} 813 \end{enumerate} 814 815 816 \section{\texorpdfstring{\LstKeywordStyle{case} Clause}{case Clause}} 817 818 C restricts the ©case© clause of a ©switch© statement to a single value. 819 For multiple ©case© clauses associated with the same statement, it is necessary to have multiple ©case© clauses rather than multiple values. 820 Requiring a ©case© clause for each value does not seem to be in the spirit of brevity normally associated with C. 821 Therefore, the ©case© clause is extended with a list of values, as in: 822 \begin{quote2} 823 \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} 824 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ 825 \begin{cfa} 826 switch ( i ) { 827 case ®1, 3, 5®: 828 ... 829 case ®2, 4, 6®: 830 ... 831 } 832 \end{cfa} 833 & 834 \begin{cfa} 835 switch ( i ) { 836 case 1: case 3 : case 5: 837 ... 838 case 2: case 4 : case 6: 839 ... 840 } 841 \end{cfa} 842 & 843 \begin{cfa} 844 845 // odd values 846 847 // even values 848 849 850 \end{cfa} 851 \end{tabular} 852 \end{quote2} 853 In addition, two forms of subranges are allowed to specify case values: a new \CFA form and an existing GNU C form.\footnote{ 854 The GNU C form \emph{requires} spaces around the ellipse.} 855 \begin{quote2} 856 \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} 857 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{GNU C}} \\ 858 \begin{cfa} 859 switch ( i ) { 860 case ®1~5:® 861 ... 862 case ®10~15:® 863 ... 864 } 865 \end{cfa} 866 & 867 \begin{cfa} 868 switch ( i ) 869 case ®1 ... 5®: 870 ... 871 case ®10 ... 15®: 872 ... 873 } 874 \end{cfa} 875 & 876 \begin{cfa} 877 878 // 1, 2, 3, 4, 5 879 880 // 10, 11, 12, 13, 14, 15 881 882 883 \end{cfa} 884 \end{tabular} 885 \end{quote2} 886 Lists of subranges are also allowed. 887 \begin{cfa} 888 case ®1~5, 12~21, 35~42®: 889 \end{cfa} 890 891 892 \section{\texorpdfstring{\LstKeywordStyle{with} Clause / Statement}{with Clause / Statement}} 893 \label{s:WithClauseStatement} 937 } 938 \end{C++} 939 Object-oriented nesting of member functions in a \lstinline[language=C++]@class/struct@ allows eliding \lstinline[language=C++]@this->@ because of lexical scoping. 940 However, for other aggregate parameters, qualification is necessary: 941 \begin{cfa} 942 struct T { double m, n; }; 943 int S::f( T & t ) { §\C{// multiple aggregate parameters}§ 944 c; i; d; §\C{\color{red}// this--{\textgreater}.c, this--{\textgreater}.i, this--{\textgreater}.d}§ 945 ®t.®m; ®t.®n; §\C{// must qualify}§ 946 } 947 \end{cfa} 948 949 To simplify the programmer experience, \CFA provides a ©with© statement (see Pascal~\cite[\S~4.F]{Pascal}) to elide aggregate qualification to fields by opening a scope containing the field identifiers. 950 Hence, the qualified fields become variables with the side-effect that it is easier to optimizing field references in a block. 951 \begin{cfa} 952 void f( S & this ) ®with ( this )® { §\C{// with statement}§ 953 c; i; d; §\C{\color{red}// this.c, this.i, this.d}§ 954 } 955 \end{cfa} 956 with the generality of opening multiple aggregate-parameters: 957 \begin{cfa} 958 void f( S & s, T & t ) ®with ( s, t )® { §\C{// multiple aggregate parameters}§ 959 c; i; d; §\C{\color{red}// s.c, s.i, s.d}§ 960 m; n; §\C{\color{red}// t.m, t.n}§ 961 } 962 \end{cfa} 963 964 In detail, the ©with© statement has the form: 965 \begin{cfa} 966 §\emph{with-statement}§: 967 'with' '(' §\emph{expression-list}§ ')' §\emph{compound-statement}§ 968 \end{cfa} 969 and may appear as the body of a function or nested within a function body. 970 Each expression in the expression-list provides a type and object. 971 The type must be an aggregate type. 972 (Enumerations are already opened.) 973 The object is the implicit qualifier for the open structure-fields. 974 975 All expressions in the expression list are open in parallel within the compound statement. 976 This semantic is different from Pascal, which nests the openings from left to right. 977 The difference between parallel and nesting occurs for fields with the same name and type: 978 \begin{cfa} 979 struct S { int ®i®; int j; double m; } s, w; 980 struct T { int ®i®; int k; int m; } t, w; 981 with ( s, t ) { 982 j + k; §\C{// unambiguous, s.j + t.k}§ 983 m = 5.0; §\C{// unambiguous, t.m = 5.0}§ 984 m = 1; §\C{// unambiguous, s.m = 1}§ 985 int a = m; §\C{// unambiguous, a = s.i }§ 986 double b = m; §\C{// unambiguous, b = t.m}§ 987 int c = s.i + t.i; §\C{// unambiguous, qualification}§ 988 (double)m; §\C{// unambiguous, cast}§ 989 } 990 \end{cfa} 991 For parallel semantics, both ©s.i© and ©t.i© are visible, so ©i© is ambiguous without qualification; 992 for nested semantics, ©t.i© hides ©s.i©, so ©i© implies ©t.i©. 993 \CFA's ability to overload variables means fields with the same name but different types are automatically disambiguated, eliminating most qualification when opening multiple aggregates. 994 Qualification or a cast is used to disambiguate. 995 996 There is an interesting problem between parameters and the function-body ©with©, \eg: 997 \begin{cfa} 998 void ?{}( S & s, int i ) with ( s ) { §\C{// constructor}§ 999 ®s.i = i;® j = 3; m = 5.5; §\C{// initialize fields}§ 1000 } 1001 \end{cfa} 1002 Here, the assignment ©s.i = i© means ©s.i = s.i©, which is meaningless, and there is no mechanism to qualify the parameter ©i©, making the assignment impossible using the function-body ©with©. 1003 To solve this problem, parameters are treated like an initialized aggregate: 1004 \begin{cfa} 1005 struct Params { 1006 S & s; 1007 int i; 1008 } params; 1009 \end{cfa} 1010 and implicitly opened \emph{after} a function-body open, to give them higher priority: 1011 \begin{cfa} 1012 void ?{}( S & s, int ®i® ) with ( s ) ®with( §\emph{\color{red}params}§ )® { 1013 s.i = ®i®; j = 3; m = 5.5; 1014 } 1015 \end{cfa} 1016 Finally, a cast may be used to disambiguate among overload variables in a ©with© expression: 1017 \begin{cfa} 1018 with ( w ) { ... } §\C{// ambiguous, same name and no context}§ 1019 with ( (S)w ) { ... } §\C{// unambiguous, cast}§ 1020 \end{cfa} 1021 and ©with© expressions may be complex expressions with type reference (see Section~\ref{s:References}) to aggregate: 1022 % \begin{cfa} 1023 % struct S { int i, j; } sv; 1024 % with ( sv ) { §\C{// implicit reference}§ 1025 % S & sr = sv; 1026 % with ( sr ) { §\C{// explicit reference}§ 1027 % S * sp = &sv; 1028 % with ( *sp ) { §\C{// computed reference}§ 1029 % i = 3; j = 4; §\C{\color{red}// sp--{\textgreater}i, sp--{\textgreater}j}§ 1030 % } 1031 % i = 2; j = 3; §\C{\color{red}// sr.i, sr.j}§ 1032 % } 1033 % i = 1; j = 2; §\C{\color{red}// sv.i, sv.j}§ 1034 % } 1035 % \end{cfa} 894 1036 895 1037 In \Index{object-oriented} programming, there is an implicit first parameter, often names \textbf{©self©} or \textbf{©this©}, which is elided. … … 897 1039 class C { 898 1040 int i, j; 899 int mem() { §\C{\color{red}// implicit "this" parameter}§900 i = 1; §\C{\color{red}// this->i}§901 j = 2; §\C{\color{red}// this->j}§1041 int mem() { §\C{\color{red}// implicit "this" parameter}§ 1042 i = 1; §\C{\color{red}// this->i}§ 1043 j = 2; §\C{\color{red}// this->j}§ 902 1044 } 903 1045 } 904 1046 \end{C++} 905 Since CFA is non-object-oriented, the equivalent object-oriented program looks like:1047 Since \CFA is non-object-oriented, the equivalent object-oriented program looks like: 906 1048 \begin{cfa} 907 1049 struct S { int i, j; }; 908 int mem( S & ®this® ) {§\C{// explicit "this" parameter}§909 ®this.®i = 1; §\C{// "this" is not elided}§1050 int mem( S & ®this® ) { §\C{// explicit "this" parameter}§ 1051 ®this.®i = 1; §\C{// "this" is not elided}§ 910 1052 ®this.®j = 2; 911 1053 } 912 1054 \end{cfa} 913 but it is cumbersome having to write "©this.©"many times in a member.1055 but it is cumbersome having to write ``©this.©'' many times in a member. 914 1056 915 1057 \CFA provides a ©with© clause/statement (see Pascal~\cite[\S~4.F]{Pascal}) to elided the "©this.©" by opening a scope containing field identifiers, changing the qualified fields into variables and giving an opportunity for optimizing qualified references. 916 1058 \begin{cfa} 917 int mem( S & this ) ®with this® {§\C{// with clause}§918 i = 1; §\C{\color{red}// this->i}§919 j = 2; §\C{\color{red}// this->j}§1059 int mem( S & this ) ®with( this )® { §\C{// with clause}§ 1060 i = 1; §\C{\color{red}// this.i}§ 1061 j = 2; §\C{\color{red}// this.j}§ 920 1062 } 921 1063 \end{cfa} … … 923 1065 \begin{cfa} 924 1066 struct T { double m, n; }; 925 int mem2( S & this1, T &this2 ) ®with this1, this2® {1067 int mem2( S & this1, T & this2 ) ®with( this1, this2 )® { 926 1068 i = 1; j = 2; 927 1069 m = 1.0; n = 2.0; … … 934 1076 struct S1 { ... } s1; 935 1077 struct S2 { ... } s2; 936 ®with s1® { // with statement1078 ®with( s1 )® { §\C{// with statement}§ 937 1079 // access fields of s1 without qualification 938 ®with s2® { // nesting1080 ®with s2® { §\C{// nesting}§ 939 1081 // access fields of s1 and s2 without qualification 940 1082 } … … 951 1093 struct S { int i; int j; double m; } a, c; 952 1094 struct T { int i; int k; int m } b, c; 953 ®with a, b® { 954 j + k; §\C{// unambiguous, unique names define unique types}§ 955 i; §\C{// ambiguous, same name and type}§ 956 a.i + b.i; §\C{// unambiguous, qualification defines unique names}§ 957 m; §\C{// ambiguous, same name and no context to define unique type}§ 958 m = 5.0; §\C{// unambiguous, same name and context defines unique type}§ 959 m = 1; §\C{// unambiguous, same name and context defines unique type}§ 960 } 961 ®with c® { ... } §\C{// ambiguous, same name and no context}§ 962 ®with (S)c® { ... } §\C{// unambiguous, same name and cast defines unique type}§ 963 \end{cfa} 964 1095 with( a, b ) 1096 { 1097 } 1098 \end{cfa} 1099 1100 \begin{comment} 965 1101 The components in the "with" clause 966 1102 … … 987 1123 the "with" to be implemented because I hate having to type all those object 988 1124 names for fields. It's a great way to drive people away from the language. 1125 \end{comment} 989 1126 990 1127 … … 996 1133 Non-local transfer can cause stack unwinding, \ie non-local routine termination, depending on the kind of raise. 997 1134 \begin{cfa} 998 exception_t E {}; §\C{// exception type}§1135 exception_t E {}; §\C{// exception type}§ 999 1136 void f(...) { 1000 ... throw E{}; ... §\C{// termination}§1001 ... throwResume E{}; ... §\C{// resumption}§1137 ... throw E{}; ... §\C{// termination}§ 1138 ... throwResume E{}; ... §\C{// resumption}§ 1002 1139 } 1003 1140 try { 1004 1141 f(...); 1005 } catch( E e ; §boolean-predicate§ ) { §\C[8cm]{// termination handler}§1142 } catch( E e ; §boolean-predicate§ ) { §\C[8cm]{// termination handler}§ 1006 1143 // recover and continue 1007 } catchResume( E e ; §boolean-predicate§ ) { §\C{// resumption handler}\CRT§1144 } catchResume( E e ; §boolean-predicate§ ) { §\C{// resumption handler}\CRT§ 1008 1145 // repair and return 1009 1146 } finally { … … 1046 1183 1047 1184 1048 \section{ Declarations}1049 \label{s: Declarations}1185 \section{Alternative Declarations} 1186 \label{s:AlternativeDeclarations} 1050 1187 1051 1188 C declaration syntax is notoriously confusing and error prone. 1052 1189 For example, many C programmers are confused by a declaration as simple as: 1053 \begin{ quote2}1190 \begin{cquote} 1054 1191 \begin{tabular}{@{}ll@{}} 1055 1192 \begin{cfa} … … 1059 1196 \raisebox{-0.75\totalheight}{\input{Cdecl}} 1060 1197 \end{tabular} 1061 \end{ quote2}1198 \end{cquote} 1062 1199 Is this an array of 5 pointers to integers or a \Index{pointer} to an array of 5 integers? 1063 The fact this declaration is unclear to many C programmers means there are\Index{productivity} and \Index{safety} issues even for basic programs.1200 If there is any doubt, it implies \Index{productivity} and \Index{safety} issues even for basic programs. 1064 1201 Another example of confusion results from the fact that a routine name and its parameters are embedded within the return type, mimicking the way the return value is used at the routine's call site. 1065 1202 For example, a routine returning a \Index{pointer} to an array of integers is defined and used in the following way: 1066 1203 \begin{cfa} 1067 int ®(*®f®())[®5®]® {...}; §\C{ definition}§1068 ... ®(*®f®())[®3®]® += 1; §\C{ usage}§1204 int ®(*®f®())[®5®]® {...}; §\C{// definition}§ 1205 ... ®(*®f®())[®3®]® += 1; §\C{// usage}§ 1069 1206 \end{cfa} 1070 1207 Essentially, the return type is wrapped around the routine name in successive layers (like an \Index{onion}). … … 1075 1212 In the following example, \R{red} is the base type and \B{blue} is qualifiers. 1076 1213 The \CFA declarations move the qualifiers to the left of the base type, \ie move the blue to the left of the red, while the qualifiers have the same meaning but are ordered left to right to specify a variable's type. 1077 \begin{ quote2}1214 \begin{cquote} 1078 1215 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 1079 1216 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ … … 1090 1227 \end{cfa} 1091 1228 \end{tabular} 1092 \end{ quote2}1229 \end{cquote} 1093 1230 The only exception is \Index{bit field} specification, which always appear to the right of the base type. 1094 1231 % Specifically, the character ©*© is used to indicate a pointer, square brackets ©[©\,©]© are used to represent an array or function return value, and parentheses ©()© are used to indicate a routine parameter. 1095 1232 However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list. 1096 1233 For instance, variables ©x© and ©y© of type \Index{pointer} to integer are defined in \CFA as follows: 1097 \begin{ quote2}1234 \begin{cquote} 1098 1235 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 1099 1236 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ … … 1106 1243 \end{cfa} 1107 1244 \end{tabular} 1108 \end{ quote2}1245 \end{cquote} 1109 1246 The downside of this semantics is the need to separate regular and \Index{pointer} declarations: 1110 \begin{ quote2}1247 \begin{cquote} 1111 1248 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 1112 1249 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ … … 1121 1258 \end{cfa} 1122 1259 \end{tabular} 1123 \end{ quote2}1260 \end{cquote} 1124 1261 which is \Index{prescribing} a safety benefit. 1125 1262 Other examples are: 1126 \begin{ quote2}1263 \begin{cquote} 1127 1264 \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} 1128 1265 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ … … 1160 1297 \end{cfa} 1161 1298 \end{tabular} 1162 \end{ quote2}1299 \end{cquote} 1163 1300 1164 1301 All type qualifiers, \eg ©const©, ©volatile©, etc., are used in the normal way with the new declarations and also appear left to right, \eg: 1165 \begin{ quote2}1302 \begin{cquote} 1166 1303 \begin{tabular}{@{}l@{\hspace{1em}}l@{\hspace{1em}}l@{}} 1167 1304 \multicolumn{1}{c@{\hspace{1em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{1em}}}{\textbf{C}} \\ … … 1181 1318 \end{cfa} 1182 1319 \end{tabular} 1183 \end{ quote2}1320 \end{cquote} 1184 1321 All declaration qualifiers, \eg ©extern©, ©static©, etc., are used in the normal way with the new declarations but can only appear at the start of a \CFA routine declaration,\footnote{\label{StorageClassSpecifier} 1185 1322 The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature.~\cite[\S~6.11.5(1)]{C11}} \eg: 1186 \begin{ quote2}1323 \begin{cquote} 1187 1324 \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} 1188 1325 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ … … 1202 1339 \end{cfa} 1203 1340 \end{tabular} 1204 \end{ quote2}1341 \end{cquote} 1205 1342 1206 1343 The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-routine ©sizeof©: 1207 \begin{ quote2}1344 \begin{cquote} 1208 1345 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 1209 1346 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ 1210 1347 \begin{cfa} 1211 y = ( ®* int®)x;1212 i = sizeof( ®[ 5 ] * int®);1348 y = (* int)x; 1349 i = sizeof([ 5 ] * int); 1213 1350 \end{cfa} 1214 1351 & 1215 1352 \begin{cfa} 1216 y = ( ®int *®)x;1217 i = sizeof( ®int * [ 5 ]®);1353 y = (int *)x; 1354 i = sizeof(int * [ 5 ]); 1218 1355 \end{cfa} 1219 1356 \end{tabular} 1220 \end{ quote2}1357 \end{cquote} 1221 1358 1222 1359 Finally, new \CFA declarations may appear together with C declarations in the same program block, but cannot be mixed within a specific declaration. 1223 1360 Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style. 1224 Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX systems. 1225 1226 1227 \section{Exponentiation Operator} 1228 1229 C, \CC, and Java (and many other programming languages) have no exponentiation operator\index{exponentiation!operator}\index{operator!exponentiation}, \ie $x^y$, and instead use a routine, like \Indexc{pow}, to perform the exponentiation operation. 1230 \CFA extends the basic operators with the exponentiation operator ©?\?©\index{?\\?@\lstinline$?\?$} and ©?\=?©\index{?\\=?@\lstinline$?\=?$}, as in, ©x \ y© and ©x \= y©, which means $x^y$ and $x \leftarrow x^y$. 1231 The priority of the exponentiation operator is between the cast and multiplicative operators, so that ©w * (int)x \ (int)y * z© is parenthesized as ©((w * (((int)x) \ ((int)y))) * z)©. 1232 1233 As for \Index{division}, there are exponentiation operators for integral and floating-point types, including the builtin \Index{complex} types. 1234 Unsigned integral exponentiation\index{exponentiation!unsigned integral} is performed with repeated multiplication\footnote{The multiplication computation is optimized to $O(\log y)$.} (or shifting if the base is 2). 1235 Signed integral exponentiation\index{exponentiation!signed integral} is performed with repeated multiplication (or shifting if the base is 2), but yields a floating-point result because $x^{-y}=1/x^y$. 1236 Hence, it is important to designate exponent integral-constants as unsigned or signed: ©3 \ 3u© return an integral result, while ©3 \ 3© returns a floating-point result. 1237 Floating-point exponentiation\index{exponentiation!floating point} is performed using \Index{logarithm}s\index{exponentiation!logarithm}, so the base cannot be negative. 1238 \begin{cfa} 1239 sout | 2 ®\® 8u | 4 ®\® 3u | -4 ®\® 3u | 4 ®\® -3 | -4 ®\® -3 | 4.0 ®\® 2.1 | (1.0f+2.0fi) ®\® (3.0f+2.0fi) | endl; 1240 256 64 -64 0.015625 -0.015625 18.3791736799526 0.264715-1.1922i 1241 \end{cfa} 1242 Parenthesis are necessary for the complex constants or the expresion is parsed as ©1.0f+(2.0fi \ 3.0f)+2.0fi©. 1243 The exponentiation operator is available for all the basic types, but for user-defined types, only the integral-computation versions are available. 1244 For returning an integral value, the user type ©T© must define multiplication, ©*©, and one, ©1©; 1245 for returning a floating-point value, an additional divide of type ©T© into a ©double© returning a ©double© (©double ?/?( double, T )©) is necessary for negative exponents. 1361 Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX-like systems. 1246 1362 1247 1363 … … 1261 1377 A program \newterm{object} is a region of data storage in the execution environment, the contents of which can represent values. 1262 1378 In most cases, objects are located in memory at an address, and the variable name for an object is an implicit address to the object generated by the compiler and automatically dereferenced, as in: 1263 \begin{ quote2}1379 \begin{cquote} 1264 1380 \begin{tabular}{@{}ll@{\hspace{2em}}l@{}} 1265 1381 \begin{cfa} … … 1279 1395 \end{cfa} 1280 1396 \end{tabular} 1281 \end{ quote2}1397 \end{cquote} 1282 1398 where the right example is how the compiler logically interprets the variables in the left example. 1283 1399 Since a variable name only points to one address during its lifetime, it is an \Index{immutable} \Index{pointer}; … … 1285 1401 In general, variable addresses are stored in instructions instead of loaded from memory, and hence may not occupy storage. 1286 1402 These approaches are contrasted in the following: 1287 \begin{ quote2}1403 \begin{cquote} 1288 1404 \begin{tabular}{@{}l|l@{}} 1289 1405 \multicolumn{1}{c|}{explicit variable address} & \multicolumn{1}{c}{implicit variable address} \\ … … 1303 1419 \end{cfa} 1304 1420 \end{tabular} 1305 \end{ quote2}1421 \end{cquote} 1306 1422 Finally, the immutable nature of a variable's address and the fact that there is no storage for the variable pointer means pointer assignment\index{pointer!assignment}\index{assignment!pointer} is impossible. 1307 1423 Therefore, the expression ©x = y© has only one meaning, ©*x = *y©, \ie manipulate values, which is why explicitly writing the dereferences is unnecessary even though it occurs implicitly as part of \Index{instruction decoding}. … … 1310 1426 (Similarly, an integer variable can contain multiple integer literals during its lifetime versus an integer constant representing a single literal during its lifetime, and like a variable name, may not occupy storage if the literal is embedded directly into instructions.) 1311 1427 Hence, a pointer occupies memory to store its current address, and the pointer's value is loaded by dereferencing, \eg: 1312 \begin{ quote2}1428 \begin{cquote} 1313 1429 \begin{tabular}{@{}l@{\hspace{2em}}l@{}} 1314 1430 \begin{cfa} … … 1322 1438 \raisebox{-0.5\totalheight}{\input{pointer2.pstex_t}} 1323 1439 \end{tabular} 1324 \end{ quote2}1440 \end{cquote} 1325 1441 1326 1442 Notice, an address has a \Index{duality}\index{address!duality}: a location in memory or the value at that location. … … 1331 1447 \end{cfa} 1332 1448 Algol68 infers the following dereferencing ©*p2 = *p1 + x©, because adding the arbitrary integer value in ©x© to the address of ©p1© and storing the resulting address into ©p2© is an unlikely operation. 1333 Unfortunately, automatic dereferencing does not work in all cases, and so some mechanism is necessary to fix incorrect choices. 1449 Unfortunately, automatic dereferencing does not work in all cases, and so some mechanism is necessary to fix incorrect choices. 1334 1450 1335 1451 Rather than inferring dereference, most programming languages pick one implicit dereferencing semantics, and the programmer explicitly indicates the other to resolve address-duality. … … 1427 1543 The position of the ©const© qualifier \emph{after} the pointer/reference qualifier causes confuse for C programmers. 1428 1544 The ©const© qualifier cannot be moved before the pointer/reference qualifier for C style-declarations; 1429 \CFA-style declarations (see \VRef{s: Declarations}) attempt to address this issue:1430 \begin{ quote2}1545 \CFA-style declarations (see \VRef{s:AlternativeDeclarations}) attempt to address this issue: 1546 \begin{cquote} 1431 1547 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 1432 1548 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ … … 1441 1557 \end{cfa} 1442 1558 \end{tabular} 1443 \end{ quote2}1559 \end{cquote} 1444 1560 where the \CFA declaration is read left-to-right. 1445 1561 … … 1519 1635 \begin{cfa} 1520 1636 void f( int i ); 1521 void (* fp)( int ); §\C{// routine pointer}§1637 void (* fp)( int ); §\C{// routine pointer}§ 1522 1638 fp = f; §\C{// reference initialization}§ 1523 1639 fp = &f; §\C{// pointer initialization}§ … … 1546 1662 \begin{itemize} 1547 1663 \item 1548 if ©R© is an \Index{rvalue} of type ©T & $_1$...&$_r$© where $r \ge 1$ references (©&© symbols) than ©&R© has type ©T ®*®&$_{\color{red}2}$...&$_{\color{red}r}$©, \ie ©T© pointer with $r-1$ references (©&© symbols).1549 1550 \item 1551 if ©L© is an \Index{lvalue} of type ©T & $_1$...&$_l$© where $l \ge 0$ references (©&© symbols) then ©&L© has type ©T ®*®&$_{\color{red}1}$...&$_{\color{red}l}$©, \ie ©T© pointer with $l$ references (©&© symbols).1664 if ©R© is an \Index{rvalue} of type ©T &©$_1\cdots$ ©&©$_r$, where $r \ge 1$ references (©&© symbols), than ©&R© has type ©T ®*®&©$_{\color{red}2}\cdots$ ©&©$_{\color{red}r}$, \ie ©T© pointer with $r-1$ references (©&© symbols). 1665 1666 \item 1667 if ©L© is an \Index{lvalue} of type ©T &©$_1\cdots$ ©&©$_l$, where $l \ge 0$ references (©&© symbols), than ©&L© has type ©T ®*®&©$_{\color{red}1}\cdots$ ©&©$_{\color{red}l}$, \ie ©T© pointer with $l$ references (©&© symbols). 1552 1668 \end{itemize} 1553 1669 The following example shows the first rule applied to different \Index{rvalue} contexts: … … 1596 1712 1597 1713 \item 1598 lvalue to reference conversion: \lstinline[deletekeywords=lvalue] $lvalue-type cv1 T$converts to ©cv2 T &©, which allows implicitly converting variables to references.1714 lvalue to reference conversion: \lstinline[deletekeywords=lvalue]@lvalue-type cv1 T@ converts to ©cv2 T &©, which allows implicitly converting variables to references. 1599 1715 \begin{cfa} 1600 1716 int x, &r = ®x®, f( int & p ); // lvalue variable (int) convert to reference (int &) … … 1898 2014 \end{cfa} 1899 2015 This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa). 1900 Like C, it is possible to declare multiple routine-prototypes in a single declaration, where the return type is distributed across \emph{all} routine names in the declaration list (see~\VRef{s: Declarations}), \eg:2016 Like C, it is possible to declare multiple routine-prototypes in a single declaration, where the return type is distributed across \emph{all} routine names in the declaration list (see~\VRef{s:AlternativeDeclarations}), \eg: 1901 2017 \begin{cfa} 1902 2018 C : const double bar1(), bar2( int ), bar3( double ); … … 2073 2189 Default arguments and overloading (see Section 24) are complementary. 2074 2190 While in theory default arguments can be simulated with overloading, as in: 2075 \begin{ quote2}2191 \begin{cquote} 2076 2192 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 2077 2193 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{default arguments}} & \multicolumn{1}{c}{\textbf{overloading}} \\ … … 2088 2204 \end{cfa} 2089 2205 \end{tabular} 2090 \end{ quote2}2206 \end{cquote} 2091 2207 the number of required overloaded routines is linear in the number of default values, which is unacceptable growth. 2092 2208 In general, overloading should only be used over default arguments if the body of the routine is significantly different. … … 2166 2282 struct T t; 2167 2283 } s; 2168 2284 2169 2285 2170 2286 … … 2225 2341 The following program in undefined in \CFA (and Indexc{gcc}) 2226 2342 \begin{cfa} 2227 [* [int]( int )] foo() { §\C{// int (* foo())( int )}§2343 [* [int]( int )] foo() { §\C{// int (* foo())( int )}§ 2228 2344 int ®i® = 7; 2229 2345 int bar( int p ) { … … 2234 2350 } 2235 2351 int main() { 2236 * [int]( int ) fp = foo(); §\C{// int (* fp)( int )}§2352 * [int]( int ) fp = foo(); §\C{// int (* fp)( int )}§ 2237 2353 sout | fp( 3 ) | endl; 2238 2354 } 2239 2355 \end{cfa} 2240 because 2356 because 2241 2357 2242 2358 Currently, there are no \Index{lambda} expressions, \ie unnamed routines because routine names are very important to properly select the correct routine. … … 2273 2389 In the latter approach, additional return values are passed as pointer parameters. 2274 2390 A pointer parameter is assigned inside the routine to emulate a return. 2275 For example, consider C's \Indexc{modf} function, which returns the integral and fractional part of a floating -pointvalue.2391 For example, consider C's \Indexc{modf} function, which returns the integral and fractional part of a floating value. 2276 2392 \begin{cfa} 2277 2393 double modf( double x, double * i ); §\C{// from include math.h}§ … … 2996 3112 2997 3113 The common case is printing out a sequence of variables separated by whitespace. 2998 \begin{ quote2}3114 \begin{cquote} 2999 3115 \begin{tabular}{@{}l@{\hspace{3em}}l@{}} 3000 3116 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{\CC}} \\ … … 3017 3133 \end{cfa} 3018 3134 \end{tabular} 3019 \end{ quote2}3135 \end{cquote} 3020 3136 The \CFA form has half the characters of the \CC form, and is similar to \Index*{Python} I/O with respect to implicit separators. 3021 3137 Similar simplification occurs for \Index{tuple} I/O, which prints all tuple values separated by ``\lstinline[showspaces=true]@, @''. … … 3029 3145 Finally, \CFA uses the logical-or operator for I/O as it is the lowest-priority overloadable operator, other than assignment. 3030 3146 Therefore, fewer output expressions require parenthesis. 3031 \begin{ quote2}3147 \begin{cquote} 3032 3148 \begin{tabular}{@{}ll@{}} 3033 3149 \textbf{\CFA:} … … 3048 3164 \end{cfa} 3049 3165 \end{tabular} 3050 \end{ quote2}3166 \end{cquote} 3051 3167 There is a weak similarity between the \CFA logical-or operator and the Shell pipe-operator for moving data, where data flows in the correct direction for input but the opposite direction for output. 3052 3168 … … 3278 3394 sout | sepDisable | 1 | 2 | 3 | endl; // globally turn off implicit separator 3279 3395 sout | sepEnable | 1 | 2 | 3 | endl; // globally turn on implicit separator 3280 3396 3281 3397 sout | 1 | sepOff | 2 | 3 | endl; // locally turn on implicit separator 3282 3398 sout | sepDisable | 1 | sepOn | 2 | 3 | endl; // globally turn off implicit separator … … 3421 3537 int id; 3422 3538 float size; 3423 Parts * optionalParts;3539 Parts * optionalParts; 3424 3540 }; 3425 3541 … … 3635 3751 3636 3752 Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization ex\-pression type. 3637 \begin{ quote2}3753 \begin{cquote} 3638 3754 \begin{tabular}{@{}l@{\hspace{3em}}ll@{}} 3639 3755 \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CC}} & \multicolumn{1}{c}{\textbf{\Indexc{gcc}}} \\ … … 3659 3775 \end{cfa} 3660 3776 \end{tabular} 3661 \end{ quote2}3777 \end{cquote} 3662 3778 The two important capabilities are: 3663 3779 \begin{itemize} … … 3807 3923 3808 3924 generic(type T) 3809 typedef int (* predicate)(T);3925 typedef int (* predicate)(T); 3810 3926 generic(type Captured, type T) 3811 typedef void (* callback)(Captured, T);3927 typedef void (* callback)(Captured, T); 3812 3928 3813 3929 generic(type T) 3814 void find(int length, T * array,3930 void find(int length, T * array, 3815 3931 predicate(T) p, callback(void *, T)f) { 3816 3932 int i; … … 3836 3952 struct LinkedListElem { 3837 3953 T elem; 3838 LinkedListElem(T) * next;3954 LinkedListElem(T) * next; 3839 3955 }; 3840 3956 3841 LinkedListElem *++?(LinkedListElem ** elem) {3842 return * elem = elem->next;3957 LinkedListElem *++?(LinkedListElem ** elem) { 3958 return * elem = elem->next; 3843 3959 } 3844 3960 3845 3961 generic (type T) 3846 3962 struct LinkedList { 3847 LinkedListElem(T) * head;3963 LinkedListElem(T) * head; 3848 3964 unsigned int size; 3849 3965 } 3850 3966 3851 3967 generic (type T | bool ?==?(T, T)) 3852 bool contains(LinkedList(T) * list, T elem) {3853 for(LinkedListElem * iter = list->head; iter != 0; ++iter) {3968 bool contains(LinkedList(T) * list, T elem) { 3969 for(LinkedListElem * iter = list->head; iter != 0; ++iter) { 3854 3970 if (iter->elem == elem) return true; 3855 3971 } … … 4064 4180 // transferring requires mutual exclusion and calls deleteJob 4065 4181 4066 void transferJob(mutex Worker & from, Worker &to) {4182 void transferJob(mutex Worker & from, Worker & to) { 4067 4183 ... 4068 4184 deleteJob(j); … … 5002 5118 #include <unistd.h> 5003 5119 } 5004 size_t fileSize( const char * path ) {5120 size_t fileSize( const char * path ) { 5005 5121 struct stat s; 5006 5122 stat(path, &s); … … 5039 5155 #[link(name = "libc")] 5040 5156 extern { 5041 fn stat(path: * const u8,5042 buf: * mut stat_t) -> c_int;5043 } 5044 fn fileSize(path: * const u8) -> size_t5157 fn stat(path: * const u8, 5158 buf: * mut stat_t) -> c_int; 5159 } 5160 fn fileSize(path: * const u8) -> size_t 5045 5161 { 5046 5162 unsafe { … … 5064 5180 generic(type T, type N | 5065 5181 { int ?<?(N, N); }) 5066 T * maximize(N (*f)(const T&),5182 T * maximize(N (*f)(const T&), 5067 5183 int n, T *a) { 5068 T * bestX = NULL;5184 T * bestX = NULL; 5069 5185 N bestN; 5070 5186 for (int i = 0; i < n; i++) { … … 5078 5194 } 5079 5195 5080 string * longest(int n, string *p)5196 string * longest(int n, string *p) 5081 5197 { 5082 5198 return maximize(length, n, p); … … 5086 5202 \begin{cfa} 5087 5203 template<typename T, typename F> 5088 T * maximize(const F &f,5204 T * maximize(const F &f, 5089 5205 int n, T *a) { 5090 5206 typedef decltype(f(a[0])) N; 5091 T * bestX = NULL;5207 T * bestX = NULL; 5092 5208 N bestN; 5093 5209 for (int i = 0; i < n; i++) { … … 5101 5217 } 5102 5218 5103 string * longest(int n, string *p) {5219 string * longest(int n, string *p) { 5104 5220 return maximize( 5105 5221 [](const string &s) { … … 5259 5375 \begin{cfa} 5260 5376 task Nonzero { 5261 int * data;5377 int * data; 5262 5378 int start; 5263 5379 int end; … … 5722 5838 \CFA introduces the following new keywords. 5723 5839 5724 \begin{ quote2}5840 \begin{cquote} 5725 5841 \input{../refrat/keywords} 5726 \end{ quote2}5842 \end{cquote} 5727 5843 5728 5844 … … 5731 5847 5732 5848 \Celeven prescribes the following standard header-files~\cite[\S~7.1.2]{C11} and \CFA adds to this list: 5733 \begin{ quote2}5849 \begin{cquote} 5734 5850 \begin{tabular}{@{}llllll|l@{}} 5735 5851 \multicolumn{6}{c|}{C11} & \multicolumn{1}{c}{\CFA} \\ … … 5791 5907 \end{tabular} 5792 5908 \end{tabular} 5793 \end{ quote2}5909 \end{cquote} 5794 5910 For the prescribed head-files, \CFA uses header interposition to wraps these includes in an ©extern "C"©; 5795 5911 hence, names in these include files are not mangled\index{mangling!name} (see~\VRef{s:Interoperability}). … … 5851 5967 void * memalign( size_t align, size_t size );§\indexc{memalign}§ 5852 5968 int posix_memalign( void ** ptr, size_t align, size_t size );§\indexc{posix_memalign}§ 5853 }5854 5855 // §\CFA§ safe equivalents, i.e., implicit size specification5856 forall( dtype T | sized(T) ) T * malloc( void );5857 forall( dtype T | sized(T) ) T * calloc( size_t dim );5858 forall( dtype T | sized(T) ) T * realloc( T * ptr, size_t size );5859 forall( dtype T | sized(T) ) T * memalign( size_t align );5860 forall( dtype T | sized(T) ) T * aligned_alloc( size_t align );5861 forall( dtype T | sized(T) ) int posix_memalign( T ** ptr, size_t align );5862 5863 // §\CFA§ safe general allocation, fill, resize, array5864 forall( dtype T | sized(T) ) T * alloc( void );§\indexc{alloc}§5865 forall( dtype T | sized(T) ) T * alloc( char fill );5866 forall( dtype T | sized(T) ) T * alloc( size_t dim );5867 forall( dtype T | sized(T) ) T * alloc( size_t dim, char fill );5868 forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim );5869 forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim, char fill );5870 5871 // §\CFA§ safe general allocation, align, fill, array5872 forall( dtype T | sized(T) ) T * align_alloc( size_t align );5873 forall( dtype T | sized(T) ) T * align_alloc( size_t align, char fill );5874 forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim );5875 forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim, char fill );5876 5969 5877 5970 // C unsafe initialization/copy 5878 extern "C" {5879 5971 void * memset( void * dest, int c, size_t size ); 5880 5972 void * memcpy( void * dest, const void * src, size_t size ); 5881 5973 } 5882 5974 5975 forall( dtype T | sized(T) ) { 5976 // §\CFA§ safe equivalents, i.e., implicit size specification 5977 T * malloc( void ); 5978 T * calloc( size_t dim ); 5979 T * realloc( T * ptr, size_t size ); 5980 T * memalign( size_t align ); 5981 T * aligned_alloc( size_t align ); 5982 int posix_memalign( T ** ptr, size_t align ); 5983 5984 // §\CFA§ safe general allocation, fill, resize, array 5985 T * alloc( void );§\indexc{alloc}§ 5986 T * alloc( char fill ); 5987 T * alloc( size_t dim ); 5988 T * alloc( size_t dim, char fill ); 5989 T * alloc( T ptr[], size_t dim ); 5990 T * alloc( T ptr[], size_t dim, char fill ); 5991 5992 // §\CFA§ safe general allocation, align, fill, array 5993 T * align_alloc( size_t align ); 5994 T * align_alloc( size_t align, char fill ); 5995 T * align_alloc( size_t align, size_t dim ); 5996 T * align_alloc( size_t align, size_t dim, char fill ); 5997 5883 5998 // §\CFA§ safe initialization/copy, i.e., implicit size specification 5884 forall( dtype T | sized(T) )T * memset( T * dest, char c );§\indexc{memset}§5885 forall( dtype T | sized(T) )T * memcpy( T * dest, const T * src );§\indexc{memcpy}§5999 T * memset( T * dest, char c );§\indexc{memset}§ 6000 T * memcpy( T * dest, const T * src );§\indexc{memcpy}§ 5886 6001 5887 6002 // §\CFA§ safe initialization/copy array 5888 forall( dtype T | sized(T) ) T * memset( T dest[], size_t dim, char c ); 5889 forall( dtype T | sized(T) ) T * memcpy( T dest[], const T src[], size_t dim ); 6003 T * amemset( T dest[], char c, size_t dim ); 6004 T * amemcpy( T dest[], const T src[], size_t dim ); 6005 } 5890 6006 5891 6007 // §\CFA§ allocation/deallocation and constructor/destructor … … 5903 6019 5904 6020 5905 \subsection{ Conversion}6021 \subsection{String to Value Conversion} 5906 6022 5907 6023 \leavevmode … … 5947 6063 forall( otype T | { int ?<?( T, T ); } ) 5948 6064 void qsort( const T * arr, size_t dim );§\indexc{qsort}§ 6065 6066 forall( otype E | { int ?<?( E, E ); } ) { 6067 E * bsearch( E key, const E * vals, size_t dim );§\indexc{bsearch}§ §\C{// location}§ 6068 size_t bsearch( E key, const E * vals, size_t dim );§\C{// position}§ 6069 E * bsearchl( E key, const E * vals, size_t dim );§\indexc{bsearchl}§ 6070 size_t bsearchl( E key, const E * vals, size_t dim ); 6071 E * bsearchu( E key, const E * vals, size_t dim );§\indexc{bsearchu}§ 6072 size_t bsearchu( E key, const E * vals, size_t dim ); 6073 } 6074 6075 forall( otype K, otype E | { int ?<?( K, K ); K getKey( const E & ); } ) { 6076 E * bsearch( K key, const E * vals, size_t dim ); 6077 size_t bsearch( K key, const E * vals, size_t dim ); 6078 E * bsearchl( K key, const E * vals, size_t dim ); 6079 size_t bsearchl( K key, const E * vals, size_t dim ); 6080 E * bsearchu( K key, const E * vals, size_t dim ); 6081 size_t bsearchu( K key, const E * vals, size_t dim ); 6082 } 6083 6084 forall( otype E | { int ?<?( E, E ); } ) { 6085 void qsort( E * vals, size_t dim );§\indexc{qsort}§ 6086 } 5949 6087 \end{cfa} 5950 6088 … … 5973 6111 \leavevmode 5974 6112 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 5975 void rand48seed( long int s );§\indexc{rand48seed}§ 5976 char rand48();§\indexc{rand48}§ 5977 int rand48(); 5978 unsigned int rand48(); 5979 long int rand48(); 5980 unsigned long int rand48(); 5981 float rand48(); 5982 double rand48(); 5983 float _Complex rand48(); 5984 double _Complex rand48(); 5985 long double _Complex rand48(); 6113 void srandom( unsigned int seed );§\indexc{srandom}§ 6114 char random( void );§\indexc{random}§ 6115 char random( char u ); §\C{// [0,u)}§ 6116 char random( char l, char u ); §\C{// [l,u)}§ 6117 int random( void ); 6118 int random( int u ); §\C{// [0,u)}§ 6119 int random( int l, int u ); §\C{// [l,u)}§ 6120 unsigned int random( void ); 6121 unsigned int random( unsigned int u ); §\C{// [0,u)}§ 6122 unsigned int random( unsigned int l, unsigned int u ); §\C{// [l,u)}§ 6123 long int random( void ); 6124 long int random( long int u ); §\C{// [0,u)}§ 6125 long int random( long int l, long int u ); §\C{// [l,u)}§ 6126 unsigned long int random( void ); 6127 unsigned long int random( unsigned long int u ); §\C{// [0,u)}§ 6128 unsigned long int random( unsigned long int l, unsigned long int u ); §\C{// [l,u)}§ 6129 float random( void ); §\C{// [0.0, 1.0)}§ 6130 double random( void ); §\C{// [0.0, 1.0)}§ 6131 float _Complex random( void ); §\C{// [0.0, 1.0)+[0.0, 1.0)i}§ 6132 double _Complex random( void ); §\C{// [0.0, 1.0)+[0.0, 1.0)i}§ 6133 long double _Complex random( void ); §\C{// [0.0, 1.0)+[0.0, 1.0)i}§ 5986 6134 \end{cfa} 5987 6135 … … 6359 6507 double scalbln( double, long int ); 6360 6508 long double scalbln( long double, long int ); 6509 \end{cfa} 6510 6511 6512 \section{Time Keeping} 6513 \label{s:TimeKeeping} 6514 6515 6516 %\subsection{\texorpdfstring{\protect\lstinline@Duration@}{Duration}} 6517 \subsection{\texorpdfstring{\LstBasicStyle{Duration}}{Duration}} 6518 \label{s:Duration} 6519 6520 \leavevmode 6521 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 6522 struct Duration { 6523 int64_t tv; §\C{// nanoseconds}§ 6524 }; 6525 6526 void ?{}( Duration & dur ); 6527 void ?{}( Duration & dur, zero_t ); 6528 6529 Duration ?=?( Duration & dur, zero_t ); 6530 6531 Duration +?( Duration rhs ); 6532 Duration ?+?( Duration & lhs, Duration rhs ); 6533 Duration ?+=?( Duration & lhs, Duration rhs ); 6534 6535 Duration -?( Duration rhs ); 6536 Duration ?-?( Duration & lhs, Duration rhs ); 6537 Duration ?-=?( Duration & lhs, Duration rhs ); 6538 6539 Duration ?*?( Duration lhs, int64_t rhs ); 6540 Duration ?*?( int64_t lhs, Duration rhs ); 6541 Duration ?*=?( Duration & lhs, int64_t rhs ); 6542 6543 int64_t ?/?( Duration lhs, Duration rhs ); 6544 Duration ?/?( Duration lhs, int64_t rhs ); 6545 Duration ?/=?( Duration & lhs, int64_t rhs ); 6546 double div( Duration lhs, Duration rhs ); 6547 6548 Duration ?%?( Duration lhs, Duration rhs ); 6549 Duration ?%=?( Duration & lhs, Duration rhs ); 6550 6551 _Bool ?==?( Duration lhs, Duration rhs ); 6552 _Bool ?!=?( Duration lhs, Duration rhs ); 6553 _Bool ?<? ( Duration lhs, Duration rhs ); 6554 _Bool ?<=?( Duration lhs, Duration rhs ); 6555 _Bool ?>? ( Duration lhs, Duration rhs ); 6556 _Bool ?>=?( Duration lhs, Duration rhs ); 6557 6558 _Bool ?==?( Duration lhs, zero_t ); 6559 _Bool ?!=?( Duration lhs, zero_t ); 6560 _Bool ?<? ( Duration lhs, zero_t ); 6561 _Bool ?<=?( Duration lhs, zero_t ); 6562 _Bool ?>? ( Duration lhs, zero_t ); 6563 _Bool ?>=?( Duration lhs, zero_t ); 6564 6565 Duration abs( Duration rhs ); 6566 6567 Duration ?`ns( int64_t nsec ); 6568 Duration ?`us( int64_t usec ); 6569 Duration ?`ms( int64_t msec ); 6570 Duration ?`s( int64_t sec ); 6571 Duration ?`s( double sec ); 6572 Duration ?`m( int64_t min ); 6573 Duration ?`m( double min ); 6574 Duration ?`h( int64_t hours ); 6575 Duration ?`h( double hours ); 6576 Duration ?`d( int64_t days ); 6577 Duration ?`d( double days ); 6578 Duration ?`w( int64_t weeks ); 6579 Duration ?`w( double weeks ); 6580 6581 int64_t ?`ns( Duration dur ); 6582 int64_t ?`us( Duration dur ); 6583 int64_t ?`ms( Duration dur ); 6584 int64_t ?`s( Duration dur ); 6585 int64_t ?`m( Duration dur ); 6586 int64_t ?`h( Duration dur ); 6587 int64_t ?`d( Duration dur ); 6588 int64_t ?`w( Duration dur ); 6589 6590 Duration max( Duration lhs, Duration rhs ); 6591 Duration min( Duration lhs, Duration rhs ); 6592 \end{cfa} 6593 6594 6595 %\subsection{\texorpdfstring{\protect\lstinline@\timeval@}{timeval}} 6596 \subsection{\texorpdfstring{\LstBasicStyle{timeval}}{timeval}} 6597 \label{s:timeval} 6598 6599 \leavevmode 6600 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 6601 void ?{}( timeval & t ); 6602 void ?{}( timeval & t, time_t sec, suseconds_t usec ); 6603 void ?{}( timeval & t, time_t sec ); 6604 void ?{}( timeval & t, zero_t ); 6605 void ?{}( timeval & t, Time time ); 6606 6607 timeval ?=?( timeval & t, zero_t ); 6608 timeval ?+?( timeval & lhs, timeval rhs ); 6609 timeval ?-?( timeval & lhs, timeval rhs ); 6610 _Bool ?==?( timeval lhs, timeval rhs ); 6611 _Bool ?!=?( timeval lhs, timeval rhs ); 6612 \end{cfa} 6613 6614 6615 %\subsection{\texorpdfstring{\protect\lstinline@timespec@}{timespec}} 6616 \subsection{\texorpdfstring{\LstBasicStyle{timespec}}{timespec}} 6617 \label{s:timespec} 6618 6619 \leavevmode 6620 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 6621 void ?{}( timespec & t ); 6622 void ?{}( timespec & t, time_t sec, __syscall_slong_t nsec ); 6623 void ?{}( timespec & t, time_t sec ); 6624 void ?{}( timespec & t, zero_t ); 6625 void ?{}( timespec & t, Time time ); 6626 6627 timespec ?=?( timespec & t, zero_t ); 6628 timespec ?+?( timespec & lhs, timespec rhs ); 6629 timespec ?-?( timespec & lhs, timespec rhs ); 6630 _Bool ?==?( timespec lhs, timespec rhs ); 6631 _Bool ?!=?( timespec lhs, timespec rhs ); 6632 \end{cfa} 6633 6634 6635 %\subsection{\texorpdfstring{\protect\lstinline@itimerval@}{itimerval}} 6636 \subsection{\texorpdfstring{\LstBasicStyle{itimerval}}{itimerval}} 6637 \label{s:itimerval} 6638 6639 \leavevmode 6640 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 6641 void ?{}( itimerval & itv, Duration alarm ); 6642 void ?{}( itimerval & itv, Duration alarm, Duration interval ); 6643 \end{cfa} 6644 6645 6646 %\subsection{\texorpdfstring{\protect\lstinline@Time@}{Time}} 6647 \subsection{\texorpdfstring{\LstBasicStyle{Time}}{Time}} 6648 \label{s:Time} 6649 6650 \leavevmode 6651 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 6652 struct Time { 6653 uint64_t tv; §\C{// nanoseconds since UNIX epoch}§ 6654 }; 6655 6656 void ?{}( Time & time ); 6657 void ?{}( Time & time, zero_t ); 6658 6659 Time ?=?( Time & time, zero_t ); 6660 6661 void ?{}( Time & time, timeval t ); 6662 Time ?=?( Time & time, timeval t ); 6663 6664 void ?{}( Time & time, timespec t ); 6665 Time ?=?( Time & time, timespec t ); 6666 6667 Time ?+?( Time & lhs, Duration rhs ); 6668 Time ?+?( Duration lhs, Time rhs ); 6669 Time ?+=?( Time & lhs, Duration rhs ); 6670 6671 Duration ?-?( Time lhs, Time rhs ); 6672 Time ?-?( Time lhs, Duration rhs ); 6673 Time ?-=?( Time & lhs, Duration rhs ); 6674 _Bool ?==?( Time lhs, Time rhs ); 6675 _Bool ?!=?( Time lhs, Time rhs ); 6676 _Bool ?<?( Time lhs, Time rhs ); 6677 _Bool ?<=?( Time lhs, Time rhs ); 6678 _Bool ?>?( Time lhs, Time rhs ); 6679 _Bool ?>=?( Time lhs, Time rhs ); 6680 6681 char * yy_mm_dd( Time time, char * buf ); 6682 char * ?`ymd( Time time, char * buf ) { // short form 6683 return yy_mm_dd( time, buf ); 6684 } // ymd 6685 6686 char * mm_dd_yy( Time time, char * buf ); 6687 char * ?`mdy( Time time, char * buf ) { // short form 6688 return mm_dd_yy( time, buf ); 6689 } // mdy 6690 6691 char * dd_mm_yy( Time time, char * buf ); 6692 char * ?`dmy( Time time, char * buf ) { // short form 6693 return dd_mm_yy( time, buf );; 6694 } // dmy 6695 6696 size_t strftime( char * buf, size_t size, const char * fmt, Time time ); 6697 forall( dtype ostype | ostream( ostype ) ) ostype & ?|?( ostype & os, Time time ); 6698 \end{cfa} 6699 6700 6701 \section{Clock} 6702 6703 \subsection{C time} 6704 \label{s:Ctime} 6705 6706 \leavevmode 6707 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 6708 char * ctime( time_t tp ); 6709 char * ctime_r( time_t tp, char * buf ); 6710 tm * gmtime( time_t tp ); 6711 tm * gmtime_r( time_t tp, tm * result ); 6712 tm * localtime( time_t tp ); 6713 tm * localtime_r( time_t tp, tm * result ); 6714 \end{cfa} 6715 6716 6717 %\subsection{\texorpdfstring{\protect\lstinline@Clock@}{Clock}} 6718 \subsection{\texorpdfstring{\LstBasicStyle{Clock}}{Clock}} 6719 \label{s:Clock} 6720 6721 \leavevmode 6722 \begin{cfa}[aboveskip=0pt,belowskip=0pt] 6723 struct Clock { 6724 Duration offset; §\C{// for virtual clock: contains offset from real-time}§ 6725 int clocktype; §\C{// implementation only -1 (virtual), CLOCK\_REALTIME}§ 6726 }; 6727 6728 void resetClock( Clock & clk ); 6729 void resetClock( Clock & clk, Duration adj ); 6730 void ?{}( Clock & clk ); 6731 void ?{}( Clock & clk, Duration adj ); 6732 6733 Duration getResNsec(); §\C{// with nanoseconds}§ 6734 Duration getRes(); §\C{// without nanoseconds}§ 6735 6736 Time getTimeNsec(); §\C{// with nanoseconds}§ 6737 Time getTime(); §\C{// without nanoseconds}§ 6738 Time getTime( Clock & clk ); 6739 Time ?()( Clock & clk ); 6740 timeval getTime( Clock & clk ); 6741 tm getTime( Clock & clk ); 6361 6742 \end{cfa} 6362 6743 … … 6532 6913 The following factorial programs contrast using GMP with the \CFA and C interfaces, where the output from these programs appears in \VRef[Figure]{f:MultiPrecisionFactorials}. 6533 6914 (Compile with flag \Indexc{-lgmp} to link with the GMP library.) 6534 \begin{ quote2}6915 \begin{cquote} 6535 6916 \begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}} 6536 6917 \multicolumn{1}{c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}} & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}} \\ … … 6564 6945 \end{cfa} 6565 6946 \end{tabular} 6566 \end{ quote2}6947 \end{cquote} 6567 6948 6568 6949 \begin{figure} … … 6659 7040 \end{cfa} 6660 7041 6661 6662 7042 \bibliographystyle{plain} 6663 \bibliography{ cfa}7043 \bibliography{pl} 6664 7044 6665 7045
Note:
See TracChangeset
for help on using the changeset viewer.