Pointers To Constants

Hello,
I am very new to proramming and am having a very dificult time grasping something.

I have to programs to make

1 is to Write a function named ComputeMaximum that has two parameters, both of type pointer 2 to constant double, and returns type pointer to double (NOT pointer to constant double).

2 is to Write a function named ComputeMaximum that has two parameters, both of type reference 18 to constant double, and returns type reference to double (NOT reference to constant double).

I think I have the first program correct but I am not sure if it is returning a type double as opposed to type const double.

Here it is. Can someone please let me know if I am doing this correctly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cstdlib>
#include <iostream>

using namespace std;

double ComputeMaximum(double const *num1, double const *num2)
{
    return((*num1 < *num2) ? *num2 : *num1);
}
int main()
{
    double const passingConst1 = 6.4;
    double const passingConst2 = 6.5;
    cout << ComputeMaximum(&passingConst1, &passingConst2);
    return EXIT_SUCCESS;
}
  
closed account (zb0S216C)
I see 1 problem: floating-point comparisons[1].

References:
[1] http://randomascii.wordpress.com/category/floating-point/


Wazzak
Last edited on
@ JamesFlanigan: Looks fine to me.
I personally prefer to put const before the type as in const double *num1... but it's obviously a personal preference.

I think I have the first program correct but I am not sure if it is returning a type double as opposed to type const double.
const is a keyword that you use to mark whatever you shouldn't modify by mistake -- so that the compiler can issue an error if you do.

In your example, you could add another const like below, but it's useless:
const double ComputeMaximum(double const *num1, double const *num2)

If you would return a reference, and not a value, it could be useful. But even there it's a bit awkward.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

double & func1()
{
	static double d;

	std::cout << "func1(): " << d << std::endl;
	return d;
}

const double & func2()
{
	static double d;

	std::cout << "func2(): " << d << std::endl;
	return d;
}

const double & func3()
{
	const static double d;

	std::cout << "func3(): " << d << std::endl;
	return d;
}

int main()
{
	func1() = 321.0;
//	func2() = 123.4; // ERROR
//	func3() = 987.6; // ERROR
	func1();
}

Topic archived. No new replies allowed.