Oberon (на английском языке), страница 3

PDF-файл Oberon (на английском языке), страница 3 Языки программирования (53747): Другое - 7 семестрOberon (на английском языке): Языки программирования - PDF, страница 3 (53747) - СтудИзба2019-09-19СтудИзба

Описание файла

PDF-файл из архива "Oberon (на английском языке)", который расположен в категории "". Всё это находится в предмете "языки программирования" из 7 семестр, которые можно найти в файловом архиве МГУ им. Ломоносова. Не смотря на прямую связь этого архива с МГУ им. Ломоносова, его также можно найти и в других разделах. .

Просмотр PDF-файла онлайн

Текст 3 страницы из PDF

AssignmentsThe assignment serves to replace the current value of a variable by a new value specified by anexpression. The assignment operator is written as ":=" and pronounced as becomes.assignment = designator ":=" expression.The type of the expression must be included by the type of the variable, or it must extend the typeof the variable. The following exceptions hold:1. The constant NIL can be assigned to variables of any pointer or procedure type.2. Strings can be assigned to any variable whose type is an array of characters, providedthe length of the string is less than that of the array. If a string s of length n is assignedto an array a, the result is a[i] = si for i = 0 ... n-1, and a[n] = 0X.Examples of assignments (see examples in Ch. 7):i := 0p := i = jx := i + 1k := log2(i+j)10F := log2s := {2, 3, 5, 7, 11, 13}a[i] := (x+y) * (x-y)t.key := iw[i+1].ch := "A"9.2.

Procedure callsA procedure call serves to activate a procedure. The procedure call may contain a list of actualparameters which are substituted in place of their corresponding formal parameters defined in theprocedure declaration (see Ch. 10). The correspondence is established by the positions of theparameters in the lists of actual and formal parameters respectively. There exist two kinds ofparameters: variable and value parameters.In the case of variable parameters, the actual parameter must be a designator denoting avariable. If it designates an element of a structured variable, the selector is evaluated when theformal/actual parameter substitution takes place, i.e.

before the execution of the procedure. If theparameter is a value parameter, the corresponding actual parameter must be an expression. Thisexpression is evaluated prior to the procedure activation, and the resulting value is assigned tothe formal parameter which now constitutes a local variable (see also 10.1.).ProcedureCall = designator [ActualParameters].Examples of procedure calls:ReadInt(i)(see Ch.

10)WriteInt(j*2+1, 6)INC(w[k].count)9.3. Statement sequencesStatement sequences denote the sequence of actions specified by the component statementswhich are separated by semicolons.StatementSequence = statement {";" statement}.9.4. If statementsIfStatement = IF expression THEN StatementSequence{ELSIF expression THEN StatementSequence}[ELSE StatementSequence]END.If statements specify the conditional execution of guarded statements. The Boolean expressionpreceding a statement is called its guard.

The guards are evaluated in sequence of occurrence,until one evaluates to TRUE, whereafter its associated statement sequence is executed. If noguard is satisfied, the statement sequence following the symbol ELSE is executed, if there is one.Example:IF (ch >= "A") & (ch <= "Z") THEN ReadIdentifierELSIF (ch >= "0") & (ch <= "9") THEN ReadNumberELSIF ch = 22X THEN ReadStringEND9.5. Case statementsCase statements specify the selection and execution of a statement sequence according to thevalue of an expression.

First the case expression is evaluated, then the statement sequence isexecuted whose case label list contains the obtained value. The case expression and all labelsmust be of the same type, which must be an integer type or CHAR. Case labels are constants,11and no value must occur more than once. If the value of the expression does not occur as a labelof any case, the statement sequence following the symbol ELSE is selected, if there is one.Otherwise it is considered as an error.CaseStatementCaseCaseLabelListCaseLabels====CASE expression OF case {"|" case} [ELSE StatementSequence] END.[CaseLabelList ":" StatementSequence].CaseLabels {"," CaseLabels}.ConstExpression [".." ConstExpression].Example:CASE ch OF"A" ..

"Z":| "0" .. "9":| 22X :ELSEENDReadIdentifierReadNumberReadStringSpecialCharacter9.6. While statementsWhile statements specify repetition. If the Boolean expression (guard) yields TRUE, thestatement sequence is executed. The expression evaluation and the statement execution arerepeated as long as the Boolean expression yields TRUE.WhileStatement =WHILE expression DO StatementSequence END.Examples:WHILE j > 0 DOj := j DIV 2; i := i+1ENDWHILE (t # NIL) & (t.key # i) DOt := t.leftEND9.7.

Repeat StatementsA repeat statement specifies the repeated execution of a statement sequence until a condition issatisfied. The statement sequence is executed at least once.RepeatStatement =REPEAT StatementSequence UNTIL expression.9.8. Loop statementsA loop statement specifies the repeated execution of a statement sequence. It is terminated bythe execution of any exit statement within that sequence (see 9.9).LoopStatement = LOOP StatementSequence END.Example:LOOPIF t1 = NIL THEN EXIT END ;IF k < t1.key THEN t2 := t1.left; p := TRUEELSIF k > t1.key THEN t2 := t1.right; p := FALSEELSE EXITEND ;t1 := t2END12Although while and repeat statements can be expressed by loop statements containing a singleexit statement, the use of while and repeat statements is recommended in the most frequentlyoccurring situations, where termination depends on a single condition determined either at thebeginning or the end of the repeated statement sequence.

The loop statement is useful toexpress cases with several termination conditions and points.9.9. Return and exit statementsA return statement consists of the symbol RETURN, possibly followed by an expression. Itindicates the termination of a procedure, and the expression specifies the result of a functionprocedure. Its type must be identical to the result type specified in the procedure heading (seeCh. 10).Function procedures require the presence of a return statement indicating the result value. Theremay be several, although only one will be executed.

In proper procedures, a return statement isimplied by the end of the procedure body. An explicit return statement therefore appears as anadditional (probably exceptional) termination point.An exit statement consists of the symbol EXIT. It specifies termination of the enclosing loopstatement and continuation with the statement following that loop statement. Exit statements arecontextually, although not syntactically bound to the loop statement which contains them.9.10. With statementsIf a pointer variable or a variable parameter with record structure is of a type T0, it may bedesignated in the heading of a with clause together with a type T that is an extension of T0.

Thenthe variable is guarded within the with statement as if it had been declared of type T. The withstatement assumes a role similar to the type guard, extending the guard over an entire statementsequence. It may be regarded as a regional type guard.WithStatement = WITH qualident ":" qualident DO StatementSequence END .Example:WITH t: CenterNode DO name := t.name; L := t.subnode END10. Procedure declarationsProcedure declarations consist of a procedure heading and a procedure body.

The headingspecifies the procedure identifier, the formal parameters, and the result type (if any). The bodycontains declarations and statements. The procedure identifier is repeated at the end of theprocedure declaration.There are two kinds of procedures, namely proper procedures and function procedures. The latterare activated by a function designator as a constituent of an expression, and yield a result that isan operand in the expression. Proper procedures are activated by a procedure call.

The functionprocedure is distinguished in the declaration by indication of the type of its result following theparameter list. Its body must contain a RETURN statement which defines the result of thefunction procedure.All constants, variables, types, and procedures declared within a procedure body are local to theprocedure. The values of local variables are undefined upon entry to the procedure. Sinceprocedures may be declared as local objects too, procedure declarations may be nested.In addition to its formal parameters and locally declared objects, the objects declared in theenvironment of the procedure are also visible in the procedure (with the exception of thoseobjects that have the same name as an object declared locally).The use of the procedure identifier in a call within its declaration implies recursive activation of theprocedure.13ProcedureDeclaration = ProcedureHeading ";" ProcedureBody ident.ProcedureHeading = PROCEDURE identdef [FormalParameters].ProcedureBody = DeclarationSequence [BEGIN StatementSequence] END.ForwardDeclaration = PROCEDURE "^" identdef [FormalParameters].DeclarationSequence = {CONST {ConstantDeclaration ";"} |TYPE {TypeDeclaration ";"} | VAR {VariableDeclaration ";"}}{ProcedureDeclaration ";" | ForwardDeclaration ";"}.A forward declaration serves to allow forward references to a procedure that appears later in thetext in full.

The actual declaration - which specifies the body - must indicate the same parametersand result type (if any) as the forward declaration, and it must be within the same scope.10.1. Formal parametersFormal parameters are identifiers which denote actual parameters specified in the procedure call.The correspondence between formal and actual parameters is established when the procedure iscalled. There are two kinds of parameters, namely value and variable parameters.

The kind isindicated in the formal parameter list. Value parameters stand for local variables to which theresult of the evaluation of the corresponding actual parameter is assigned as initial value.Variable parameters correspond to actual parameters that are variables, and they stand for thesevariables. Variable parameters are indicated by the symbol VAR, value parameters by theabsence of the symbol VAR. A function procedure without parameters must have an emptyparameter list.

It must be called by a function designator whose actual parameter list is emptytoo.Formal parameters are local to the procedure, i.e. their scope is the program text whichconstitutes the procedure declaration.FormalParameters = "(" [FPSection {";" FPSection}] ")" [":" qualident].FPSection = [VAR] ident {"," ident} ":" FormalType.FormalType = {ARRAY OF} qualident.The type of each formal parameter is specified in the parameter list. For variable parameters, itmust be identical to the corresponding actual parameter's type, except in the case of a record,where it must be a base type of the corresponding actual parameter's type. For value parameters,the rule of assignment holds (see 9.1). If the formal parameter's type is specified asARRAY OF Tthe parameter is said to be an open array parameter, and the corresponding actual parametermay be any array with element type T.If a formal parameter specifies a procedure type, then the corresponding actual parameter mustbe either a procedure declared at level 0 or a variable (or parameter) of that procedure type.

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5301
Авторов
на СтудИзбе
417
Средний доход
с одного платного файла
Обучение Подробнее