function's return value

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
raysa
New poster
Posts: 40
Joined: Wed Dec 18, 2002 4:23 pm
Location: Indonesia

function's return value

Post 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
Viktoras Jucikas
New poster
Posts: 22
Joined: Sun Oct 20, 2002 6:41 pm
Location: Lithuania
Contact:

Post 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.
Viktoras Jucikas
New poster
Posts: 22
Joined: Sun Oct 20, 2002 6:41 pm
Location: Lithuania
Contact:

Post by Viktoras Jucikas »

should be:

// i == 2 && j == 1 (not 2 )
raysa
New poster
Posts: 40
Joined: Wed Dec 18, 2002 4:23 pm
Location: Indonesia

Post 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
Sebasti
New poster
Posts: 10
Joined: Sun Apr 13, 2003 11:41 pm
Contact:

Post 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
Post Reply

Return to “C++”