ISO/IEC 2011 - All rights reservedISO/IEC9899:2011 (E)5.1.2.2.1 Program startupThe function called at program startup is named main. The implementation declares noprototype for this function.It shall be defined with a return type of int and with noparameters:int main(void)(/*...*/)or with two parameters (referred to here as argc and argv, though any names may beused, as they are local to the function in which they are declared):int main(int argc, char *argv[j) ( /...*/)or equivalent;10) or in some other implementation-defined manner.2If they are declared, the parameters to the main function shall obey the followingconstraints:- Thevalue of argc shall be nonnegativeargv[argc] shall beanull pointer.If the value of argc is greater than zero, the array members argv[o] throughargv[argc-1] inclusive shall contain pointers to strings, which are givenimplementation-definedvalues by the host environment priortoprogram startup.Theintent is to supply to the program information determined prior to program startupfrom elsewhere in the hosted environment.If the host environment is not capable ofsupplying strings with letters in both uppercase and lowercase, the implementationshall ensure that the strings are received in lowercase.If the value of argc is greater than zero, the string pointed to by argv[o]-represents the program name; argv[o][o] shall be the null character if theprogram name is not available from the host environment. If the value of arge isgreater than one, the strings pointed to by argv[1] through argv[argc-1]represent theprogram parameters. The parameters argc and argv and the strings pointed to by the argv array shallbe modifiable by the program, and retain their last-stored values between programstartupand programtermination5.1.2.2.2 Program executionIn a hosted environment, a program may use all the functions, macros, type definitions,and objects described in the library clause (clause7).10)Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written aschar ** argy,andsoon13$5.1.2.2.2Environment
© ISO/IEC 2011 − All rights reserved ISO/IEC 9899:2011 (E) 5.1.2.2.1 Program startup 1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters: int main(void) { /* . */ } or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared): int main(int argc, char *argv[]) { /* . */ } or equivalent;10) or in some other implementation-defined manner. 2 If they are declared, the parameters to the main function shall obey the following constraints: — The value of argc shall be nonnegative. — argv[argc] shall be a null pointer. — If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase. — If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters. — The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination. 5.1.2.2.2 Program execution 1 In a hosted environment, a program may use all the functions, macros, type definitions, and objects described in the library clause (clause 7). 10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char ** argv, and so on. §5.1.2.2.2 Environment 13
ISO/IEC9899:2011 (E)ISO/IEC2011-All rights reserved5.1.2.2.3Program terminationIf the return type of the main function is a type compatible with int,a return from theinitial calltothemainfunctionisequivalentto callingtheexitfunction withthevaluereturned by the main function as its argument;ll) reaching the } that terminates themain function returns avalue of o.If the return type is not compatible with int, thetermination status returned to the host environment is unspecified.Forward references: definition ofterms (7.1.1),the exit function (7.22.4.4)5.1.2.3ProgramexecutionThe semantic descriptions in this International Standard describe the behavior of anabstract machine in which issues of optimization are irrelevant.2Accessing a volatile object, modifying an object, modifying a file, or calling a functionthat does any of those operations are all side effects,12) which are changes in the state ofthe execution environment. Evaluation of an expression in general includes both valuecomputations and initiation of side effects. Value computation for an lvalue expressionincludes determining the identity of the designated object.3Sequenced before is an asymmetric, transitive, pair-wise relation between evaluationsexecuted by a single thread, which induces a partial order among those evaluations.Given any two evaluations A and B, if A is sequenced before B, then the execution of Ashall precedethe execution of B. (Conversely,if A is sequenced before B, then B issequenced afiter A.) If A is not sequenced before or after B,then A and B areunsequenced.Evaluations A and B are indeterminately sequenced when A is sequencedeither before or after B, but it is unspecified which 13) The presence of a sequence pointbetweentheevaluationofexpressionsAandBimpliesthateveryvaluecomputationandside effect associated with A is sequenced before every value computation and side effectassociated withB.(A summaryofthe sequence points is given in annexC)4Intheabstractmachine,allexpressionsareevaluatedasspecifiedbythesemantics.Anactual implementationneednot evaluatepart of an expression ifitcan deducethat itsvalue is not used and that no needed side effects are produced (including any caused by11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in mainwill have ended in theformer case, even where they would nothave in the latter.12)The IEC 60559 standard for binary floating-point arithmetic requires certain user-accessible statusflags and control modes.Floating-point operations implicitly set the status flags; modes affect resultvalues of floating-point operations.Implementations that support such floating-point state arerequired to regard changes to it as side effectssee annexF for details.Thefloating-pointenvironmentlibrary<fenv.h>providesa programmingfacilityfor indicating when these sideeffectsmatter,freeingtheimplementationsinothercases.13)The executions of unsequenced evaluations can interleave.Indeterminately sequenced evaluationscannot interleave, but can be executed in any order.14Environment$5.1.2.3
ISO/IEC 9899:2011 (E) © ISO/IEC 2011 − All rights reserved 5.1.2.2.3 Program termination 1 If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified. Forward references: definition of terms (7.1.1), the exit function (7.22.4.4). 5.1.2.3 Program execution 1 The semantic descriptions in this International Standard describe the behavior of an abstract machine in which issues of optimization are irrelevant. 2 Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, 12) which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object. 3 Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread, which induces a partial order among those evaluations. Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. (Conversely, if A is sequenced before B, then B is sequenced after A.) If A is not sequenced before or after B, then A and B are unsequenced. Evaluations A and B are indeterminately sequenced when A is sequenced either before or after B, but it is unspecified which.13) The presence of a sequence point between the evaluation of expressions A and B implies that every value computation and side effect associated with A is sequenced before every value computation and side effect associated with B. (A summary of the sequence points is given in annex C.) 4 In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by 11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main will have ended in the former case, even where they would not have in the latter. 12) The IEC 60559 standard for binary floating-point arithmetic requires certain user-accessible status flags and control modes. Floating-point operations implicitly set the status flags; modes affect result values of floating-point operations. Implementations that support such floating-point state are required to regard changes to it as side effects — see annex F for details. The floating-point environment library <fenv.h> provides a programming facility for indicating when these side effects matter, freeing the implementations in other cases. 13) The executions of unsequenced evaluations can interleave. Indeterminately sequenced evaluations cannot interleave, but can be executed in any order. 14 Environment §5.1.2.3
CISO/IEC 2011 -All rights reservedISO/IEC9899:2011 (E)calling a function or accessing a volatile object)When the processing of the abstract machine is interrupted by receipt of a signal, the5values of objects that are neither lock-free atomic objects nor of type volatilesig_atomic_t are unspecified, as is the state of the floating-point environment.Thevalue of any object modified by the handler that is neither a lock-free atomic object nor oftype volatile sig_ atomic t becomes indeterminate when the handler exits, asdoes the state of the floating-point environment if it is modified by the handler and notrestored to its original stateTheleastrequirementsonaconformingimplementationare:6Accesses to volatileobjects are evaluated strictly according to the rules of the abstract一machine-At program termination, all data written into files shall be identical to the result thatexecution of the program accordingto the abstract semantics would have produced.The input and output dynamics of interactive devices shall take place as specified in7.21.3. The intent of these requirements is that unbuffered or line-buffered outputappearas soon aspossible,to ensurethatpromptingmessages actuallyappearpriortoa program waiting for input.This is the observablebehavior of the program.7What constitutes an interactivedeviceis implementation-defineddMore stringent correspondences between abstract and actual semantics may be defined byeach implementation.EXAMPLE1An implementation might define a one-to-one correspondence between abstract and actual9semantics:at every sequence point, the values of the actual objects would agree with those specified by theabstractsemantics.Thekeyword volatilewould then be redundant.10Alternatively,an implementationmightperformvarious optimizationswithin eachtranslation unit,suchthatthe actual semantics would agreewiththe abstract semanticsonlywhen making function calls acrosstranslation unit boundaries. In such an implementation,at the time of each function entry and functionreturn where the calling function and the called function are in differenttranslation units,the values ofallexternally linked objects and of all objects accessiblevia pointersthereinwould agree with the abstractsemantics.Furthermore,at the time of each such function entry the values of the parameters of the calledfunction and of all objects accessible via pointers therein would agree with the abstract semantics.In thistypeof implementation,objects referredtoby interrupt serviceroutinesactivatedbythesignal functionwould require explicit specification of volatile storage, as well as other implementation-definedrestrictions.EXAMPLE2Inexecutingthefragment11char cl, c2;/*..*/cl = cl + c2;the"integer promotions"require that theabstractmachinepromote thevalue of each variableto int sizeand then add thetwoints and truncatethe sum.Provided the addition of two chars can bedonewithout15$5.1.2.3Environment
© ISO/IEC 2011 − All rights reserved ISO/IEC 9899:2011 (E) calling a function or accessing a volatile object). 5 When the processing of the abstract machine is interrupted by receipt of a signal, the values of objects that are neither lock-free atomic objects nor of type volatile sig_atomic_t are unspecified, as is the state of the floating-point environment. The value of any object modified by the handler that is neither a lock-free atomic object nor of type volatile sig_atomic_t becomes indeterminate when the handler exits, as does the state of the floating-point environment if it is modified by the handler and not restored to its original state. 6 The least requirements on a conforming implementation are: — Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine. — At program termination, all data written into files shall be identical to the result that execution of the program according to the abstract semantics would have produced. — The input and output dynamics of interactive devices shall take place as specified in 7.21.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input. This is the observable behavior of the program. 7 What constitutes an interactive device is implementation-defined. 8 More stringent correspondences between abstract and actual semantics may be defined by each implementation. 9 EXAMPLE 1 An implementation might define a one-to-one correspondence between abstract and actual semantics: at every sequence point, the values of the actual objects would agree with those specified by the abstract semantics. The keyword volatile would then be redundant. 10 Alternatively, an implementation might perform various optimizations within each translation unit, such that the actual semantics would agree with the abstract semantics only when making function calls across translation unit boundaries. In such an implementation, at the time of each function entry and function return where the calling function and the called function are in different translation units, the values of all externally linked objects and of all objects accessible via pointers therein would agree with the abstract semantics. Furthermore, at the time of each such function entry the values of the parameters of the called function and of all objects accessible via pointers therein would agree with the abstract semantics. In this type of implementation, objects referred to by interrupt service routines activated by the signal function would require explicit specification of volatile storage, as well as other implementation-defined restrictions. 11 EXAMPLE 2 In executing the fragment char c1, c2; /* . */ c1 = c1 + c2; the ‘‘integer promotions’’ require that the abstract machine promote the value of each variable to int size and then add the two ints and truncate the sum. Provided the addition of two chars can be done without §5.1.2.3 Environment 15
ISO/IEC9899:2011 (E)ISO/IEC 2011-All rights reservedoverflow,orwith overflowwrapping silentlytoproducethe correct result,theactual execution need onlyproducethesameresult,possiblyomittingthepromotions.EXAMPLE3Similarly,inthefragment12float f1, f2;double d;/*.. */f1 = f2 * d;the multiplication may be executed using single-precision arithmetic if the implementation can ascertainthattheresultwouldbethe sameas ifit wereexecuted usingdouble-precision arithmetic(forexample,ifdwerereplacedbytheconstant2.o,whichhastypedouble)EXAMPLE4Implementations employing wideregisters haveto take caretohonor appropriate13semantics.Values are independent of whether theyare represented in a register orin memory.Forexample,animplicitspillingofaregisterisnotpermittedtoalterthevalue.Also,anexplicitstoreand loadisrequiredtoroundtotheprecision ofthe storagetype.In particular,castsand assignments arerequiredtoperformtheir specifiedconversion,Forthefragmentdouble dl, d2;float f;dl= f=expression;d2=(float)expression;thevalues assigned tod1 andd2 are required tohavebeen convertedtof1oatEXAMPLE5 Rearrangementforfloating-point expressions is often restrictedbecauseof limitations in14 precision aswell asrange.The implementationcannotgenerallyapplythemathematical associativerulesfor addition or multiplication, nor the distributive rule, because of roundoff error, even in the absence ofoverflowandunderflow.Likewise,implementationscannotgenerallyreplacedecimal constants inordertorearrange expressions.In thefollowingfragment,rearrangements suggested by mathematical rules for realnumbersareoftennotvalid(seeF.9)double x, Y, zi/ *.. */x = (x * y) * z; // notequivalenttox *= y * z;(x -y) +y ; // notequivalent toz = x;-=x+x*yi// notequivalent toz = x * (1.o + y);Z=x/5.0;// notequivalenttoy=x 0.2;yEXAMPLE6To illustrate the grouping behavior ofexpressions, in thefollowing fragment15int a,b;/*..*/a=a+32760+b+5;theexpressionstatementbehaves exactlythesameasa=(((a+32760)+b)+5);duetotheassociativity and precedenceof these operators.Thus,theresultof thesum (a+3276o)isnext added to b, and that result is then added to 5 which results in the value assigned to a. On a machine inwhichoverflowsproduceanexplicittrap and inwhichtherangeofvalues representablebyanint is[-32768, +32767], theimplementationcannot rewritethis expression asa=((a+b)+32765);since if the valuesfora andb were,respectively,-32754 and-15,the sum a+b would producea trap16$5.1.2.3Environment
ISO/IEC 9899:2011 (E) © ISO/IEC 2011 − All rights reserved overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only produce the same result, possibly omitting the promotions. 12 EXAMPLE 3 Similarly, in the fragment float f1, f2; double d; /* . */ f1 = f2 * d; the multiplication may be executed using single-precision arithmetic if the implementation can ascertain that the result would be the same as if it were executed using double-precision arithmetic (for example, if d were replaced by the constant 2.0, which has type double). 13 EXAMPLE 4 Implementations employing wide registers have to take care to honor appropriate semantics. Values are independent of whether they are represented in a register or in memory. For example, an implicit spilling of a register is not permitted to alter the value. Also, an explicit store and load is required to round to the precision of the storage type. In particular, casts and assignments are required to perform their specified conversion. For the fragment double d1, d2; float f; d1 = f = expression; d2 = (float) expression; the values assigned to d1 and d2 are required to have been converted to float. 14 EXAMPLE 5 Rearrangement for floating-point expressions is often restricted because of limitations in precision as well as range. The implementation cannot generally apply the mathematical associative rules for addition or multiplication, nor the distributive rule, because of roundoff error, even in the absence of overflow and underflow. Likewise, implementations cannot generally replace decimal constants in order to rearrange expressions. In the following fragment, rearrangements suggested by mathematical rules for real numbers are often not valid (see F.9). double x, y, z; /* . */ x = (x * y) * z; // not equivalent to x *= y * z; z = (x - y) + y ; // not equivalent to z = x; z = x + x * y; // not equivalent to z=x* (1.0 + y); y=x/ 5.0; // not equivalent to y=x* 0.2; 15 EXAMPLE 6 To illustrate the grouping behavior of expressions, in the following fragment int a, b; /* . */ a=a+ 32760 + b + 5; the expression statement behaves exactly the same as a = (((a + 32760) + b) + 5); due to the associativity and precedence of these operators. Thus, the result of the sum (a + 32760) is next added to b, and that result is then added to 5 which results in the value assigned to a. On a machine in which overflows produce an explicit trap and in which the range of values representable by an int is [−32768, +32767], the implementation cannot rewrite this expression as a = ((a + b) + 32765); since if the values for a and b were, respectively, −32754 and −15, the sum a+b would produce a trap 16 Environment §5.1.2.3
ISO/IEC2011-All rights reservedISO/IEC9899:2011 (E)while the original expression would not; nor can the expression be rewritten either asa=((a+32765)+b);or(a +(b + 32765));since the valuesfor a and b might have been, respectively,4 and-8 or-17 and 12.However, on a machinein which overflow silently generates some value and where positive and negative overflows cancel,theaboveexpressionstatementcanberewrittenbytheimplementationinanyof theabovewaysbecausethesame result will occur.EXAMPLE7Thegrouping of an expression does not completely determine its evaluation.In the16followingfragment#include <stdio.h>int sum;char *p;/*..*/sum = sum * 10 -0+ (*p++= getchar());theexpressionstatementisgroupedasifitwerewrittenassum=(((sum*10)-"0")+((*(p++))=(getchar()));but the actual increment of p can occur at any time between the previous sequence point and the nexsequence point (the ;), and the call to getchar can occur at any point prior to the need of its returnedvalueForward references: expressions (6.5), type qualifiers (6.7.3), statements (6.8), floatingpoint environment<fenv.h>(7.6), the signa1 function (7.14), files (7.21.3).5.1.2.4 Multi-threaded executions and data racesUnder a hosted implementation, a program can have more than one thread of execution(or thread) running concurrently. The execution of each thread proceeds as defined bythe remainder of this standard. The execution of the entire program consists of anexecution of all of its threads.14) Under a freestanding implementation, it isimplementation-defined whether a program can have more than one thread of execution2The value of an object visible to a thread T at a particular point is the initial value of theobject, a value stored in the object by T, or a value stored in the object by another thread,according to the rules below.NOTE1 In some cases, there may instead be undefined behavior. Much of this section is motivated by3the desire to support atomic operations with explicit and detailed visibility constraints.However, it alsoimplicitlysupportsasimplerviewformorerestrictedprograms.4Two expression evaluations conflict if one of them modifies a memory location and theother one reads or modifies the same memorylocation.14)The execution can usuallybeviewed as an interleavingof all of the threads.However,somekinds ofatomic operations,for example, allow executions inconsistent with a simple interleaving as describedbelow.17$5.1.2.4Environment
© ISO/IEC 2011 − All rights reserved ISO/IEC 9899:2011 (E) while the original expression would not; nor can the expression be rewritten either as a = ((a + 32765) + b); or a = (a + (b + 32765)); since the values for a and b might have been, respectively, 4 and −8 or −17 and 12. However, on a machine in which overflow silently generates some value and where positive and negative overflows cancel, the above expression statement can be rewritten by the implementation in any of the above ways because the same result will occur. 16 EXAMPLE 7 The grouping of an expression does not completely determine its evaluation. In the following fragment #include <stdio.h> int sum; char *p; /* . */ sum = sum * 10 - '0' + (*p++ = getchar()); the expression statement is grouped as if it were written as sum = (((sum * 10) - '0') + ((*(p++)) = (getchar()))); but the actual increment of p can occur at any time between the previous sequence point and the next sequence point (the ;), and the call to getchar can occur at any point prior to the need of its returned value. Forward references: expressions (6.5), type qualifiers (6.7.3), statements (6.8), floatingpoint environment <fenv.h> (7.6), the signal function (7.14), files (7.21.3). 5.1.2.4 Multi-threaded executions and data races 1 Under a hosted implementation, a program can have more than one thread of execution (or thread) running concurrently. The execution of each thread proceeds as defined by the remainder of this standard. The execution of the entire program consists of an execution of all of its threads.14) Under a freestanding implementation, it is implementation-defined whether a program can have more than one thread of execution. 2 The value of an object visible to a thread T at a particular point is the initial value of the object, a value stored in the object by T, or a value stored in the object by another thread, according to the rules below. 3 NOTE 1 In some cases, there may instead be undefined behavior. Much of this section is motivated by the desire to support atomic operations with explicit and detailed visibility constraints. However, it also implicitly supports a simpler view for more restricted programs. 4 Tw o expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location. 14) The execution can usually be viewed as an interleaving of all of the threads. However, some kinds of atomic operations, for example, allow executions inconsistent with a simple interleaving as described below. §5.1.2.4 Environment 17