Page 1 of 1

function's return value

Posted: Fri Mar 21, 2003 7:44 pm
by raysa
Hi again!
It's about function in C++... I'm just not familiar with it!
Can you tell me why my code below doesn't hit my purpose <to swap two integers> :
[cpp]#include <stdio.h>

int i,j,temp;

int swap(int a, int b)
{
temp=a;
a=b;
b=temp;

return (a,b);
}

void main()
{
int i,j;

i=1; j=2;
swap (i,j);
}[/cpp]

Thank's in advance 8)
Raysa

Posted: Fri Mar 21, 2003 8:23 pm
by Viktoras Jucikas
You should pass parameters by pointer/reference and return nothing (aka void) if you want to have some effect on them. Now it just copies a and b to stack, swaps, and after return from function stack is cleared, so a, b remain the same.

Your return statement is incorrect - you've probably meant returning both changed values, but it is not possible in C or C++ - you can return only one parameter (your statement works as comma operator takes action - but nothing happens)

Correct function should look like this (warning: not tested)
[cpp]
void swap(int& a, int& b)
{
a ^= b ^= a ^= b;
}

void main()
{
int i,j;

i=1; j=2;
swap (i,j);
// now i == 2 && j == 2
}
[/cpp]

Try reading B. Stroustrup's Annotated C++ Ref. Manual, B. Eckel's Thinking in C++, and, of course, Effective and More Effective series by S. Meyers.

Posted: Fri Mar 21, 2003 8:25 pm
by Viktoras Jucikas
should be:

// i == 2 && j == 1 (not 2 )

Posted: Sat Apr 05, 2003 3:01 pm
by raysa
Thank's!
Now I want to know how we read integers using "scanf" until the end of line or when the newline('\n') is reached...
example:

Code: Select all

2 5
1 2 3 4 5
consists of 2 inputs: integers in the first line and in the second line.
How can we separate it without taking it as 2 different string inputs <with 'gets'>?

Best regards,
Raysa

Posted: Wed Apr 16, 2003 9:09 pm
by Sebasti
Hi,

i don't know how to do using scanf, but using cin is:

if( cin.get() != '\n' ){
cin.unget();
cin >> number;
}

The standard input has a buffer, where you can go ahead and come back with the functions get and unget.

Bye