-2

In my function sumofrange I decided to output an undeclared variable just to learn the different compiler errors in C++. To my surprise, time seems to output 1 even though it is not declared anywhere.

#include <iostream>
#include <cmath>

using namespace std;

int  sumOfrange( int   lower, int  upper){
   cout<<time<<endl;
   return ((( (pow(upper,2)) + upper) - ((pow(lower,2)) + lower)) / 2);
}

int main(){  
    cout<<sumOfrange(7,100)<<endl;
    return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 4
    This is why namespaces are important and `using namespace std;` is sometimes dangerous. – ForceBru Aug 31 '17 at 14:51
  • You should read [this](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – NathanOliver Aug 31 '17 at 14:53
  • 1
    btw there is no such thing as an "undeclared variable". If it was undeclared you could not use it – 463035818_is_not_an_ai Aug 31 '17 at 14:54
  • @ForceBru Remove `using namespace std;`, and you'll get the same output for `std::cout << time << '\n';` on a lot of implementation. – Holt Aug 31 '17 at 15:09
  • 1
    Even if `using namespace std;` should probably be removed here, the real solution would be to enable your compiler warning (`-W -Wall` with clang / gcc) to obtain a warning for such code. – Holt Aug 31 '17 at 15:11
  • 3
    I disagree with the dupe target. [Removing `using namespace std;`](http://coliru.stacked-crooked.com/a/fd9c9486c617ce8d) has no effect on the issue. – nwp Aug 31 '17 at 15:11
  • BTW, the [`std::pow` function](http://en.cppreference.com/w/cpp/numeric/math/pow) is for floating point. To square numbers, use multiplication, e.g. `upper * upper` and `lower * lower`. The multiplication is more efficient since it doesn't require a function call. – Thomas Matthews Aug 31 '17 at 15:18

1 Answers1

4

You are outputting the address of a std::time function declared in a <ctime> header. You are also using a using namespace std; statement. Why that should be avoided is explained in this SO post. Depending on the compiler and the platform you might get the hexadecimal output similar to (0x)00DC52E0 if using a VC++ compiler on Windows or a number 1 if using a g++ compiler on Linux.

Ron
  • 14,674
  • 4
  • 34
  • 47