Return c что это

от admin

Return c что это

Pre-requisite: Functions in C

C return statement ends the execution of a function and returns the control to the function from where it was called. The return statement may or may not return a value depending upon the return type of the function. For example, int returns an integer value, void returns nothing, etc.

In C, we can only return a single value from the function using the return statement and we have to declare the data_type of the return value in the function definition/declaration.

Syntax:

Working of Return Statement

There are various ways to use return statements. A few are mentioned below:

1. Methods not returning a value

In C, one cannot skip the return statement when the return type of the function is non-void type. The return statement can be skipped only for void types.

A. Not using a return statement in void return type function:

While using the void function, it is not necessary to use return as the void itself means nothing(an empty value).

Return c что это

Метод может возвращать значение, какой-либо результат. В примере выше были определены два метода, которые имели тип void . Методы с таким типом не возвращают никакого значения. Они просто выполняют некоторые действия.

Но методы также могут возвращать некоторое значение. Для этого применяется оператор return , после которого идет возвращаемое значение:

Например, определим метод, который возвращает значение типа string :

Метод GetMessage имеет тип string , следовательно, он должен возвратить строку. Поэтому в теле метода используется оператор return , после которого указана возвращаемая строка.

При этом методы, которые в качестве возвращаемого типа имеют любой тип, кроме void , обязательно должны использовать оператор return для возвращения значения. Например, следующее определение метода некорректно:

Также между возвращаемым типом метода и возвращаемым значением после оператора return должно быть соответствие. Например, в следующем случае возвращаемый тип — string , но метод возвращает число (тип int), поэтому такое определение метода некорректно:

Результат методов, который возвращают значение, мы можем присвоить переменным или использовать иным образом в программе:

Метод GetMessage() возвращает значение типа string . Поэтому мы можем присвоить это значение какой-нибудь переменной типа string: string message = GetMessage();

Либо даже передать в качестве значения параметру другого метода:

В вызове PrintMessage(GetMessage()) сначада вызывается метод GetMessage() и его результат передается параметру message метода PrintMessage

После оператора return также можно указывать сложные выражения или вызовы других методов, которые возвращают определенный результат. Например, определим метод, который возвращает сумму чисел:

Метод Sum() имеет тип int , следовательно, он должен возвратить значение типа int — целое число. Поэтому в теле метода используется оператор return , после которого указано возвращаемое число (в данном случае результат суммы переменных x и y).

Сокращенная версия методов с результатом

Также мы можем сокращать методы, которые возвращают значение:

аналогичен следующему методу:

аналогичен следующему методу:

Выход из метода

Оператор return не только возвращает значение, но и производит выход из метода. Поэтому он должен определяться после остальных инструкций. Например:

С точки зрения синтаксиса данный метод корректен, однако его инструкция Console.WriteLine(«After return») не имеет смысла — она никогда не выполнится, так как до ее выполнения оператор return возвратит значение и произведет выход из метода.

Однако мы можем использовать оператор return и в методах с типом void . В этом случае после оператора return не ставится никакого возвращаемого значения (ведь метод ничего не возвращает). Типичная ситуация — в зависимости от опеределенных условий произвести выход из метода:

Здесь метод PrintPerson() в качестве параметров принимает имя и возраст пользователя. Однако в методе вначале мы проверяем, соответствует ли возраст некоторому диапазону (меньше 120 и больше 0). Если возраст находится вне этого диапазона, то выводим сообщение о недопустимом возрасте и с помощью оператора return выходим из метода. После этого метод заканчивает свою работу.

Однако если возраст корректен, то выводим информацию о пользователе на консоль. Консольный вывод:

return statement

Terminates current function and returns specified value to the caller function.

Contents

[edit] Syntax

attr-spec-seq (optional) return expression ; (1)
attr-spec-seq (optional) return ; (2)
expression expression used for initializing the return value of the function
attr-spec-seq (C23) optional list of attributes, applied to the return statement
Читать:
Как зайти в корзину в телеграмме

[edit] Explanation

If the type of the expression is different from the return type of the function, its value is converted as if by assignment to an object whose type is the return type of the function, except that overlap between object representations is permitted:

If the return type is a real floating type, the result may be represented in greater range and precision than implied by the new type.

Reaching the end of a function returning void is equivalent to return ; . Reaching the end of any other value-returning function is undefined behavior if the result of the function is used in an expression (it is allowed to discard such return value). For main , see main function.

Executing the return statement in a no-return function is undefined behavior.

The return statement in C

The return statement is used to return some value or simply pass the control to the calling function. The return statement can be used in the following two ways.

  1. return;
  2. return expression;

The first form of the return statement is used to terminate the function and pass the control to the calling function. No value from the called function is returned when this form of the return statement is used.

The following program demonstrates the use of the first form of the return statement.

Expected Output:

How it works

Let's say the user entered 17 (value of variable n ), then eligible_or_not() function is called, this function expects one argument of type int , which we have correctly supplied as n . The value of variable n is assigned to variable age . Remember age is a local variable, and thus only available inside eligible_or_not() function. if condition (age >= 18) is tested, since it is false, the statement under if block is omitted. Control passes to else statement and condition (age == 17) is tested, since it is true, statements under else if block is executed. The return statement under the else if block passes the control back to calling function i.e main() . If the return statement would not have been there in the else if block, the control would have been moved ahead to execute the statement following if-else statement.

The second form of the return statement is used to return values from a function. The expression following return can be any constant, variable, function call etc.

The following program computes the factorial of a number using a function.

Expected Output:

How it works

There is nothing extraordinary happening in the main() function, so we are only going to explain how factorial() function works. Let’s say the user entered 5, in line 18 the factorial() function is called, along with an argument of type int. In line 30, if condition (n==0) is checked, since it is false, statements inside the if block are omitted. If the condition (n==0) would have been true, then the statement return 1; (Why we are returning 1 , because factorial of 0 is 1 ) would have been executed, and the control would have been transferred back to main() function, effectively terminating the factorial() function.

In line 34, two variables f and i of type int are declared and the variable f is assigned a value of 1 .

In line 36, for loop's initialization expression is executed, i is assigned the value of n . Then the condition (i>0) is tested, since it is true, statement inside the for body is executed. At this point, the value of f is 5 . This completes the first iteration. Then update expression i— is executed. This process continues until i is greater than 0 . The following table shows the value of i and fact after each iteration.

Iteration Value of i Value of fact
1 5 5
2 4 5*4 = 20
3 3 20* 3 = 60

When i reaches 0 , the condition (i > 0) becomes false and the control breaks out of the for loop to execute statements following the loop.

In line 40, the return statement causes the factorial() function to terminate and return the value of variable f to the calling function main() .

Ezoic

report this ad

Похожие статьи