If statements

Hello Everyone!

I'm trying to create a function, or add something to the body of my main() that, whenever I pass an input integer, returns me a corresponding string, example:

1
2
3
4
5
6
7
string fn(int i)
{
    if (i == 1) return "one";
    if (i == 3) return "three";
    if (i == 9) return "nine";
    return "none";
}


Now does this take linear time in executing? i.e. does the compilere pass by the cases case by case or there's something special about if clauses?
Is switch statement the same?

If in both cases, linear time is inevitable, is there something better?

Thanks!
The time is constant (it could be considered linear, but integer comparison is such a trivial task that you wouldn't observe any linearity at all).
A switch would be the same.
Another way to do the same thing could be
1
2
3
4
5
6
string number[] = {"one", "two", "three", "four", "five"};

string fn(int i){
   if(i < 6 && i >= 0) return number[i];
   else return "none";
}
To add to hamsterman's reply:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;
string Function (int a0)
{
	a0--;
	string sa [] = {"one", "two", "three"}; // Add more numbers if you want
	return sa [a0];
}
int main ()
{
	int iInput = 0;
	while (1)
	{
		cout << "Enter a number: ";
		cin >> iInput;
		cout << endl << Function (iInput) << endl << endl;
		cin.get ();
	}
	return 0;
}
Last edited on
Topic archived. No new replies allowed.