For example, in the sentence below,
#include<iostream>
# include <cmath>
float Myabs (float x);
int main() {
float a = 2.5;
std::cout<<Myabs(a)<<std::abs(a);
a = -5.25;
std::cout<<Myabs(a)<<std::abs(a);
return 0;
}
float Myabs (float x) {return x > 0?x:-x;}
If you change this sentence as shown in the two examples below,
Example 1
#include<iostream>
float Myabs (float x);
int main() {
float a = 2.5;
std::cout<<Myabs(a)<<std::abs(a);
a = -5.25;
std::cout<<Myabs(a)<<std::abs(a);
return 0;
}
# include <cmath>
float Myabs (float x) {return x > 0?x:-x;}
Example 2
#include<iostream>
# include <cmath>
int main() {
float a = 2.5;
std::cout<<Myabs(a)<<std::abs(a);
a = -5.25;
std::cout<<Myabs(a)<<std::abs(a);
return 0;
}
float Myabs (float x);
float Myabs (float x) {return x > 0?x:-x;}
Both of them have errors in both cases.Error due to lack of declaration and error due to lack of inclusion.
Does this indicate that the include statement and declaration behave the same way from the compiler perspective?
Try the -E
compilation option.Prints source code processed by the preprocessor.The source code output by this is the source code of the C and C++ languages.You can understand that preprocessor instructions such as #include
and #define
#if
#endif
have been processed and disappeared.
First, include and declaration are different.
#include
only has the ability to capture the contents of a file during compilation.
Typically, #include
uses it to capture header files.A header file is usually a file with a declaration; iostream
and cmath
are also header files, which contain declarations such as std::cout
and std::abs
.This may be confusing.
The std::abs
declaration is described in <cmath>
.However, std::abs(a)
appears before #include<cmath>
appears, so no declaration is found and an error occurs.
Error because Myabs(a)
appears before the float Myabs(float x);
declaration.
© 2024 OneMinuteCode. All rights reserved.