Do while loop not working inside a function in C [duplicate] - c

In the following code, would anything be returned?
#include <stdio.h>
int try_this (int in);
int main (void)
{
try_this (5);
}
int try_this (int in)
{
int i = 1;
for (i = 0; i < in; i = i + 2) {
return i;
}
return i;
}
Since there's a return in the for loop, would the code just return nothing since there's nothing after the function is called? Or would i be returned as a number, like 1(because of the declaration in try_this) or 6(because of the loop)?
Thank you!!:)

When the first return statement is encountered, the function will return. It's easy to see that the function will start the loop and while i=0 it will return i. So each time you call try_this you'll get 0
Also, return 0; from main...

When you enter the for loop for the first time, i is 0 and less than the 5. Then it execute the statement return i; in for loop, which will finish executing the try_this() funciton.

What you are basically asking is that if the function will return something even though there is no code after the function call.
The answer is yes, it will return. It doesn't matter if there is code later or not. The function will return (in this case 0) It's just that there's nobody to catch it.

The function try_this() always returns 0:
i is initially set to 1
then i is set to 0 in the initial clause of the for statement
if i < in, the loop body is executed and the value of i is returned, namely 0.
otherwise the loop is skipped and the next statement is return i; so 0 is returned too.
Regarding the main function: it ignores the return value of try_this(5) and reaches the end of its body without a return statement. This is bad style and would trigger undefined behavior for any other function, but since C99 the behavior is defined as a special case for the main function and the value 0 is returned to the startup code, which exits back to the system with a termination status of 0, which means successful execution.

if you want to store the value of 'I' i would recommend you to use "while loop"
int i = 0;
while(i < in)
{
i++;
}

Related

return in a for loop C

In the following code, would anything be returned?
#include <stdio.h>
int try_this (int in);
int main (void)
{
try_this (5);
}
int try_this (int in)
{
int i = 1;
for (i = 0; i < in; i = i + 2) {
return i;
}
return i;
}
Since there's a return in the for loop, would the code just return nothing since there's nothing after the function is called? Or would i be returned as a number, like 1(because of the declaration in try_this) or 6(because of the loop)?
Thank you!!:)
When the first return statement is encountered, the function will return. It's easy to see that the function will start the loop and while i=0 it will return i. So each time you call try_this you'll get 0
Also, return 0; from main...
When you enter the for loop for the first time, i is 0 and less than the 5. Then it execute the statement return i; in for loop, which will finish executing the try_this() funciton.
What you are basically asking is that if the function will return something even though there is no code after the function call.
The answer is yes, it will return. It doesn't matter if there is code later or not. The function will return (in this case 0) It's just that there's nobody to catch it.
The function try_this() always returns 0:
i is initially set to 1
then i is set to 0 in the initial clause of the for statement
if i < in, the loop body is executed and the value of i is returned, namely 0.
otherwise the loop is skipped and the next statement is return i; so 0 is returned too.
Regarding the main function: it ignores the return value of try_this(5) and reaches the end of its body without a return statement. This is bad style and would trigger undefined behavior for any other function, but since C99 the behavior is defined as a special case for the main function and the value 0 is returned to the startup code, which exits back to the system with a termination status of 0, which means successful execution.
if you want to store the value of 'I' i would recommend you to use "while loop"
int i = 0;
while(i < in)
{
i++;
}

C - return value at index: control reaches end of non-void function

First of all: I just recently started programming in C (my first programming language) and this may be a stupid/simple question, but I was trying to implement a function which returns the value at index in an array/list. I always get this error from the compiler: "error: compiler reaches end of non-void function" even though I am returning values of type int. Thanks in advance:
int list_get(int list[], int length, int index) {
if(index <= CAPACITY){
for(int i = 0; i <= CAPACITY; i++){
if(i == index)
return list[i];
}
}
else{
printf("Index is out of range. \n");
return 0;
}
}
The compiler sees, both the return statements are under some sort of conditional block, so it tries to warn you. Nothing wrong, as such.
Consider the flow,
index <= CAPACITY is true,
for none of the iterations, i == index is true.
for loop is exited.
In that case, there's nothing to be returned....
To avoid, just move the return 0; statement out of else block. be aware of the possible side effect, if i == index check fails, it will return 0.
For starters the function does not make sense. The parameter length is not used within the function. Also there is no need to include a loop that to check that index is less than or equal to the magic value CAPACITY.
The compiler issues a message because it is unable to determine that this condition
if(i == index)
will be always true provided that this condition
if(index <= CAPACITY){
is also true.
Also it is not clear how to distinguish 0 from a valid value in the array at the index.
your else statement is out of for loop.so when your for loop exits it execute statement of else and there you have written "return 0". so it won't return any value.

Is it necessary to include a return statement after my while loop in this function?

I have a function like
int myfun(int *a, int *b)
{
while(some condition)
{
if(condition) return *a + *b;
else
{
some manipulation;
}
}
return -1;
}
When first return statement in while->if part is encountered,does the control go to the function calling myfun or while loop still continues?Why is the return -1 statement needed?
After the return *a+*b the function returns that and ends. You need the return -1 because if that condition is never met, what will it return? It is a int function so it has to return something.
If some condition is not met, control will never enter the loop and proceed on to execute next line where function ends.
In this case, the function should return some value, as it does not have void return type. Hence, return -1
Yes Dear , if the condition is true for the "if" statement then the function will be returned at that point in this case . The return -1 statement is helpful and indeed necessary bcoz it take care that something will be returned even if "if" statement is never executed . If the function had been declared as void myfunc then it would surely have caused an error.
The return -1 statement is needed because some_condition may not be fullfilled at the first time, so the while loop will not be entered.
Therefore some return value has to be provided (-1 in this case).
The first return statement is only applied when the condition for it is met. If the condition is met, the return statement immediately takes the control back to the calling function, However, if for some reason the if is not satisfied, then all the iterations of the while loop are met and finally it has to return an integer value since the return type is integer, again the control flows back to the calling function.
Every end point(exit) of functions must have the return statement(if declaration of the function is like that ofcourse).The code you write is gonna be processed by the compiler so it should exactly know all possible exit points of your function depending on meeting the criteria of the branches within your function.

use of return 0; in main() in C [duplicate]

This question already has answers here:
What is the proper declaration of main in C++?
(5 answers)
In the main function of a C++ program, what does `return 0` do and mean? [duplicate]
(12 answers)
Closed 8 years ago.
I'm reading Programming in C by Brian Kernighnan an Dennis Ritchie in that(pg.25 bottom)
Here the author quotes:
The value that power computes is returned to main by the return statement. Any expression may follow return: return expression ;
But in the code he provided above:
#include <stdio.h>
int power(int m , int n);
main()
{
int i;
for (i = 0; i < 10; ++i)
printf ( " %d \t %d \t %d \n ", i, power( 2 , i), power( -3 , i));
return 0;//no. 1
}
int power(int m , int n)
{
int i, p ;
p = 1;
for (i = 1; i <= n; ++i)
p = p * m;
return p; //no. 2
}
Here I understood why he used 2. return p; in function power (i.e to get the value of p) but why does he use 1. return 0; ??
I tried removing the line return 0; And it still worked as I had thought, is there something I'm missing??
[UPDATE]
I'm sorry for not including this before but I already knew this much:
quoted in the book:
You may have noticed that there is a return statement at the end of
main. Since main is a function like any other, it may return a value
to its caller, which is in effect the environment in which the program
was executed. Typi- cally, a return value of zero implies normal
termination; non-zero values signal unusual or erroneous termination
conditions. In the interests of simplicity, we have omitted return
statements from our main functions up to this point, but we will
include them hereafter, as a reminder that programs should return
status to their environment.
Thanks to #Pascal I was able to understand the difference in both the return p; and return 0;
However my intention was never to know what return 0; was but why return was used also to know the difference between both the return statment......
In a function other than the entry point of the program, return e; indicates the result that will be sent to the caller.
A return i; statement in the main() function is a way instead for the program to communicate an exit code to the operating system. In POSIX, return 0; indicates success.
The return 0; at the end of function main() is so perfunctory that in C99, it was made optional. The } ending function main() implicitly behaves like return 0; according to the standard:
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; reaching the } that terminates the main function returns a value of 0[…]
However, in C90, there is no such exception, and it is technically undefined behavior to have an int-returning function such as main() reach the final } without a return statement. The worst that seems to happen in practice is that the program returns with an indeterminate value in the register or stack slot reserved for function results, so that the Operating System may think that the program failed when it actually succeeded.
main()'s return code is conventionally a way for programs to give the operating system an indication on whether they completed successfully or no. Conventionally a return value of zero means success, while other values are used to indicate errors.
OS's like UNIX/Linux and Windows provide ways to check such return code; in sh or bash the $? holds the return code of the last command executed, in Windows' cmd you can obtain it as %ERRORLEVEL%.
The main function of every C program should return 0 if the program worked correctly. It's a convention which you should always follow.
According to the ISO/IEC C++ Standard (14882), section 3.6.1 states that the function main should have one of the two signatures:
int main(void) { .... }
or
int main(int argc, char** argv) { .... }
Most compilers accept variants of this, such as just main() { .... } for backwards comparability, such as your example code. The return at the end of main is the value that is returned to the calling environment (typically the command shell) and it can be used to represent successful completion of the program (by return 0), or return an error code to the calling environment in case of program error.
If you leave the return off at the end of main, a return 0; is assumed.

Can anyone help me understand what's wrong with this code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
int m[1000]; //declaring global array
int added(int input){
for(int i=1;i<= input; i++){
if(i>0 && input % 2) // checking if the numbers are even...
m[i]= input; //array implementation
return m[i];
}
}
int main()
{
for(int j=2;j<54;j++){
printf("%d",m[i]);
putchar('\n');
}
return 0;
}
I'm trying to return array from a function. why isn't it working?
Implemented array in for loop.
Your main function has a for loop iterating on a variable called j, but the body of the loop is trying to use an undefined variable called i.
Your main function also never even calls your added() function.
Moreover, your added() function is kind of problematic too.
int added(int input){
for(int i=1;i<= input; i++){
if(i>0 && input % 2) // checking if the numbers are even...
m[i]= input; //array implementation
return m[i];
}
}
I code in several different languages, so I'm not sure if this is actually an issue here or not, but your return statement is within a for loop. In many languages, this won't compile because your added() function doesn't have a return statement for every possible execution path. What happens if you send added() an argument <1? added(0) or any negative int will never enter the for loop, so added() gets to the end of the function without a return statement.
Moreover, with your return within the for loop and outside the if statement, you're guaranteed to only return the result of the first for loop, so you may as well just do a nested if statement or something.
Then there's your if statement. if(i>0 && input % 2). The && returns true when both halves also return true (and that's the only time your if statement is executed). In this case, i>0 returns true every time i is a non-zero positive integer. No problem here. Meanwhile, input % 2 doesn't return a boolean. It will return an int, and in this case, it will return 0 or 1. It will return 0 on even numbers and 1 on odd numbers. And as it turns out, the integer 0 is evaluated as a boolean false here and non-zero integers are evaluated as boolean true so this is probably doing the opposite of what you want. You need to change input % 2 to ((input % 2) == 0) probably.
And finally, if m[] is declared globably, you don't actually need to return anything. main() and added() can both see the variable perfectly fine. You can modify your function to look like this:
void added(int input){
for(int i=1;i<= input; i++){
if(/*i will always be >0 in this for loop*/(input % 2) == 0)
m[i]= input;
}
return;
}
Then all you have to do is actually call added() from main and it will correctly modify the array.
You use i in main but you meant to use j, I suspect.
You are not returning an array from added(), you are returning an element m[1] from the array. The function will return m[1] at the first iteration of the for loop.
At the first iteration of the for loop i = 1, so m[1] will be whatever the input is and the function will return m[1] at return m[1].
Another problem in main(), you are using m[i] but i is not defined in main().
You never called added, you never initialized int m[1000]; hence by default the entire array has 0 - you are indexing with i in main instead of j. Return is inside the for loop.

Resources