ch3-Translate (Function prototypes in C/C++)
Chapter_3 | Return Exercise_3-1 |
Translate TCP1, p. 123-124 (translate.c, Translate.cpp)
translate.c download
#include <stdio.h> // for printf()
// int translate(float x, y); // compile error: unknown type name 'y'
int translate(float x, float y, float z);
int translate(float, float, float); // same function prototype
// int translate(int, int); // compile error: overloading not allowed in C
void func(); // indeterminate number of arguments in C
void noargs(void); // no arguments
int main()
{
float x, y, z; // OK
printf("%d\n", translate(0,1,2)); // 3
func();
func(0);
func(1,2);
noargs();
// noargs(0); // compile error: too many arguments
return 0;
}
/*
int translate(float, float, float) // compile error: parameter name omitted
{} // not complaining about no return value
*/
/*
int translate(float x, float y, float z)
{} // garbage return value, no compile or run-time error
*/
int translate(float x, float y, float z)
{
return x+y+z;
}
void func(){}
void noargs(void){}
/*
gcc translate.c -o translate
./translate
3
*/
Translate.cpp download
#include <iostream>
using std::cout;
using std::endl;
// int translate(float x, y); // compile error: 'y' has not been declared
int translate(float x, float y, float z);
int translate(int, int); // overloading in C++
void func(); // No arguments in C++
void noargs(void); // No arguments
int main()
{
float x, y, z; // OK
cout << translate(1,2) << endl; // 0, call translate(int, int)
cout << translate(1,2,3) << endl; // 1+2, translate(float, float, float)
func();
// func(0); // compile error: too many arguments
noargs();
// noargs(0); // compile error: too many arguments
return 0;
}
int translate(int, int) {return 0;}
int translate(float x, float y, float)
{
// return x+y+z; // compile error: 'z' was not declared in this scope
return x+y;
}
void func(){}
void noargs(void){}
/*
g++ Translate.cpp -o Translate
./Translate
0
3
*/
Chapter_3 | BACK_TO_TOP | Return Exercise_3-1 |
Comments
Post a Comment