void draw( int I, long L );
long sq( int s );
int main()
{
long y;
int x;
y = sq( x );
draw( x, y );
return();
}
long sq( int s )
{
return( s * s );
}
void draw( int I, long L )
{
return;
}
What is the difference between return(), return (S*S) and return? Please give an explanation.
Well:
return(); is illegal, have you tried compiling?
return(s*s) is the same as return s*s; and it tells the function what value to return.
For example, if you would have:
long x = sq(1);
//x would be 1 here
return; exits from a void function. You can't put an empty return statement inside a function with a non-void return type. Put at the end of a void function, it does nothing. But you can use it to exit the function early:
void foo()
{
if ( someCondition )
return;
statement1;
statement2;
return;
}
The first return has the effect that it will exit the function if someCondition is true. So the statements will not be executed. The second return makes no difference whatsoever.
There is hardly any difference.
Basically there are two syntaxes.
First of all:
return somethinghere;
is exactly the same as
return (somethinghere);
You can replace "somethinghere" with anything you want (as long as it qualifies with the function's return type), an equation another funciton anything that has a value, including simply nothing if the return type is "void".
If you put nothing, then it means you function returns nothing, otherwise you are returning the result of whatever you have placed there.
Related
I am writing a Queue data structure and I am not able to retain the value of the integer in the array once the value is returned in the stack. The pop function is doing exactly what it needs to do but why doesn't main get that information? What am I missing? malloc?
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
int QUE[20];
const int EMPTY = -1;
int position = -1;
int retrieve = 0;
//push, append to front of array
bool push(int num) {
if (position >= 20) return false;
position += 1;
QUE[position] = num;
return true;
}
//pop from top of array
bool pop() {
if(QUE[retrieve] == 0) return false;
int hold = QUE[retrieve];
printf("%d",hold);
retrieve ++;
return hold;
}
// PEEK
// First in first out
int main() {
push(12);
push(90);
push(22);
int t;
//why does pop equal 1
while ((t = pop()) != 0) {
printf("t = %d\n",t);
}
}
You're trying to pass two different kinds of information – a boolean state 'the pop succeeded' and an integer value popped from the queue – within the same value. That's bad; and the mismatch led you to declaring the return type as bool, which causes the resulting value of t being either zero or one (as a conversion of false or true, respectively, to the int type).
Try to split the action into testing and fetching phase, like:
bool anyItemInQueue()
{
return _add_appropriate_condition_here_;
}
int main()
{
....
while( anyItemInQueue() )
{
int t = pop();
.... // use t here
}
}
or pass another variable to receive another value:
bool pop(int *result)
{
if( anyItemInQueue() )
{
*result = QUE[retrieve];
.... // some housekeeping here
return true; // success status
}
return false; // failure status
}
int main()
{
....
int t;
while( pop( & t ) ) // point at t to receive the popped value
{
.... // use t here
}
}
It is because any non zero value is being converted to bool true and then to integer. The integer value of the bool true is 1
Your code has undefined behavior.
Let's consider for example the function push
//push, append to front of array
bool push(int num) {
if (position >= 20) return false;
position += 1;
QUE[position] = num;
return true;
}
and let's also assume for simplicity that the array QUE has only one element that is it is declared like
int QUE[1];
In this case the queue can only contain one pushed value due to the capacity of the array.
So after a first call of push like
push( 0 );
you will have that position is equal to 0 and the queue contains the value 0.
If to call the function a second time like for example
push( 1 );
the condition within the function
if (position >= 1) return false;
will not evaluate to true because the current value of position is 0. As a result the function will try to write the value 1 into the invalid location of the array QUE[1].
The array contains only one element but the function allows to write one more element.
Now let's consider the function pop
bool pop() {
if(QUE[retrieve] == 0) return false;
int hold = QUE[retrieve];
printf("%d",hold);
retrieve ++;
return hold;
}
and the same queue that already contains only one element equal to 0 (See the previous call push( 0 )).
As the condition of the if statement
if(QUE[retrieve] == 0) return false;
evaluates to true (the queue indeed contains the value 0 pushed on the queue early) then the function will return false as if the queue is empty though it is not empty.
So and this function is invalid.
Moreover in the loop in main
while ((t = pop()) != 0) {
printf("t = %d\n",t);
}
it seems you are trying to output values stored in the queue. However the function does not return such values. Due to the return type bool that is a typedef for the C standard type _Bool any returned value is converted either to 0 or 1.
So the program is in whole wrong.
I am trying to write a function that takes a linked list, an index and returns the value at the index+1 position.
int getData(list *l, int index) {
if(...) {
...
return result; // this could be -1
}
else {
return -1;
}
}
In C you return a value of -1 when the function fails (as a way to let the user know that the call failed because of bad input). However, because the return type of this function is int, it includes the value of -1 (-1 as a number, as well ass -2, -3 etc)
My question is: Is there a mechanism in which you can return from your function and make the user of the function aware that the returned value is in fact an error and not a value?
Return the value by passing a pointer and make the return value an error statement:
int getData(list *l, int inIndex, int* outIndex) {
if(...) {
...
*outIndex = result;
return 0;
}
else {
return -1;
}
}
/I am trying to return the 1st bit of boolean value of 10 using right shift in the cb function./
#include<stdbool.h>
bool cb(int N,int i){ //`called function`
return ((N>>i)&1)==1;
}
int main(void) { //`main function`
cb(10,1);
return 0;
}
//Status:successfully Executed,but no output.
main doesn't magically return the result of another function, you need to return the value also from main
int main(void)
{
return cb(10, 1);
}
or you can exit the program from your function with a value:
bool cb(int N,int i){ //`called function`
exit(((N>>i)&1)==1 ? EXIT_FAILURE : EXIT_SUCCESS);
}
and check the return in the console:
./yourprogram
echo $?
But notice that this is considered bad practice, we usualy return EXIT_FAILURE only when something went wrong, instead, you can print the result:
int main(void)
{
printf("%d\n", cb(10, 1));
return 0;
}
Finaly, you can use a debugger
Change your code to
Line 6 int res = cb(10, 1);
Line 7 return 0;
and start the debugger
gdb yourprogram
breakpoint 7 (after the line you want to inspect)
run
print res
So Here's your program:
#include<stdbool.h>
//`called function`
bool cb(int N,int i)
{
return ((N >> i) & 1) ==1;
}
//`main function`
int main(void)
{
cb(10,1);
return 0;
}
Your program is executing - which means that the main() function is returning successfully (a Value of 0). You also invoke cb(10,1); which calls your function declaration above (and returns a boolean: True/False). But you don't store the value of that function call, nor display the value with a printf() or cout statement.
You'll need to add more for your program to give you more noticable output.
I have the following C code:
VALUE find_index(VALUE arr, VALUE num_elements, VALUE element){
....
}
....
VALUE array_distance(VALUE arr1, VALUE arr2){
long arr1_len = RARRAY_LEN(arr1);
VALUE *c_arr2 = RARRAY_PTR(arr2);
long i;
for(i = 0; i < arr2_len; i++){
long arr1_index = find_index(arr1, arr1_len, c_arr2[i]);
....
}
}
When compiling this, I get the following error:
In function ‘VALUE array_distance(VALUE, VALUE, VALUE)’:
error: too few arguments to function ‘VALUE find_index(VALUE, VALUE, VALUE, VALUE)’
Can someone help with what is wrong here?
If you want to use your C functions in other C code inside, you need to use builder.c_raw instead of builder.c, because RubyInline actually tries to make your life easier by changing your code so you can write simple functions quickly. This is however misleading and keeps you from calling your C functions from inside other C functions, because the method signature is altered. This should get you started:
class Test
inline :C do |builder|
builder.c_raw <<-'EOC', :arity => 3
static VALUE
find_index(int argc, VALUE *argv, VALUE self) {
VALUE arr = argv[0];
VALUE num_elements = argv[1];
VALUE element = argv[2];
// actual code...
}
EOC
builder.c_raw <<-'EOC', :arity => 2
static VALUE
array_distance(int argc, VALUE *argv, VALUE self) {
long arr1_len = RARRAY_LEN(argv[0]);
VALUE *c_arr2 = RARRAY_PTR(argv[1]);
long i;
for(i = 0; i < arr2_len; i++){
VALUE[] find_index_argv = {arr1, arr1_len, c_arr2[i]};
long arr1_index = find_index(argc, find_indev_argv, self);
// more code...
}
// must have a return value!
return Qnil;
}
EOC
end
end
The return data-type of a function,whose prototype is declared in main(), is void.
It cointains an instruction return; as in
main()
{
void create(int *p);
*some code*
}
void create(node *list)
{
*some code*
return;
}
What will it return,and where will it return??
It's not going to return anything, you might have return statements in a void function to kind of alter the flow and exit from the function. ie rather than:
void do_something(int i)
{
if (i > 1) {
/* do something */
}
/* otherwise do nothing */
}
you might have:
void do_something(int i)
{
if (i <= 1)
return;
/* if haven't returned, do something */
}
In this case doesn't mean much.
return; means exit suddenly from this function returning void.
int a()
{
return 10;
}
void b()
{
return; // we have nothing to return, this is a void function.
}
void c()
{
// we don't need return; it is optional.
}
return; for a void function is not useful, it can be omitted, is optional.
However sometime it is useful, for example, for exiting a loop or a switch.
void xxx()
{
int i = 0;
while (1)
{
if (++i >= 100)
return; // we exit from the function when we get 100.
}
}
return; won't return anything, which matches the declared void return type of the function create. It will return to the caller of the function it appears in (not shown in your example), just like return EXPRESSION; will.
In this particular piece of code, return; is redundant since it appears at the very end of create, but it's useful when you want to exit a function prematurely:
void print_error(char const *errmsg)
{
if (errmsg == NULL)
// nothing to print
return;
perror(errmsg);
}
it will return from the executing function with a void return value (which means no value).