I have following macro for measuring time in header file:
#define TIMER_START(x) double ___timer__##x = (double) getTickCount();
#define TIMER_END(x) ___timer__##x = (getTickCount() - ___timer__##x) *1000 / getTickFrequency(); cout << "t" << ##x << ": " << ___timer__##x << endl;
The problem is, when I use this header file, the cout is not defined. Is there any option to use it this way? I have tried specifiing namespace but with no luck. Either ostream:: and std:: doesn't contain definition for cout.
PS: I'm working in MSVS2010.
The name cout has to be visible at the point where you invoke the macro. Writing
TIMER_START(0);
is just like writing
double ___timer__0 = (double) getTickCount();;
and the same visibility rules apply.
I suspect that changing cout to std::cout will fix the problem. Of course you'll need to include the appropriate header in any source file that invokes the macro.
Some other issues:
Identifiers starting with underscores are reserved to the implementation. I believe C++ also reserves identifiers with embedded double underscores. You're trying to avoid colliding with user-defined identifiers, but you risk colliding with compiler-defined or library-defined identifiers. It's probably not going to cause any visible problems, but you should use some other unique prefix.
The trailing semicolons in your macro definitions are redundant; you'll provide those when you invoke them:
TIMER_START(0);
TIMER_END(0);
Related
I made a Newton-Raphson Method program. But I have a question. As you see, "epsilon" and "x0" are float type and when I try to write something like "a" or "b", the program goes crazy. I want to prevent it. I want to tell "Please enter a number" to the user when something happens like this.
Can you help me about that? Thank you.
Code is below:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
#include<iostream>
#include<math.h>
#include<sstream>
#include <iomanip>
#include<time.h>
#define f(x) pow(x,5)-pow(x,4)-pow(x,3)+2*pow(x,2)
#define g(x) 5*pow(x,4)-4*pow(x,3)-3*pow(x,2)+4*x
using namespace std;
int main()
{
setlocale(LC_ALL,"turkish");
cout << "Problem 4" << endl << "---------" << endl << "Verilen y=(x^2)/(x+1) ve y=(x^3)/(x^3+2) fonksiyonlarının varsa kesim noktalarını bulan C programı\n" << endl;
float x0, x1, f0, f1, g0, epsilon;
int tahmin = 1, sinir=1000;
cout << setprecision(6)<< fixed;
bastan:
cout << "Epsilon değerini giriniz: "; //Pay attention here. My question is about here.
epsilonHata:
cin >> epsilon;
cout << endl;
hata:
cout << "İlk tahmin değerini giriniz: "; //Just like above, my question is about here too.
cin >> x0;
cout << endl;
bla bla...
}
The infinite loop problem occurs because cin and underlying ifstream expects a float in your case. By not providing a float, cin fails and the weird loop occurs. More information here.
Since you cannot control the user and you do not want the program to break if the user inputs characters, you can read the input to string instead of float. This way, no error flag is set by cin.
Then, you should convert the string to float. atof is suitable for this purpose.
#include <iostream>
#include <string>
#include <cstdlib>
...
std::string epsilon_str;
std::cin >> epsilon_str;
double epsilon = atof(epsilon_str.c_str());
From the documentation of atof:
If the first sequence of non-whitespace characters in str does not form a valid floating-point number as just defined, or if no such sequence exists because either str is empty or contains only whitespace characters, no conversion is performed and the function returns 0.0.
Other general programming issues
There are lots of headers you include. Knowing what is required for which function or class is the best practice. I assume you included them when you needed, but if you won't use setprecision, then there is no reason to #include <iomanip>.
Using define means simply copy-paste. The compiler is not aware of what you are doing. See the following example.
#define WRONG_MULTIPLY(a, b) a * b
#define CORRECTED_MULTIPLY(a, b) ((a) * (b))
...
int wrong_result = WRONG_MULTIPLY(1 + 2, 3 + 4); // 11
int corrected_result = CORRECTED_MULTIPLY(1 + 2, 3 + 4); // 21
The best practice is using functions. That is the purpose of functions.
int multiply(int a, int b) {
return a * b;
}
...
int result = multiply(1 + 2, 3 + 4);
I used uppercase letters for macros to attract attention that they are macros. Seriously, you do not want to deal with compiler errors where the cause is a macro that you are not aware of.
And at this point, I suggest going through a tutorial, like this one to understand the basic consepts.
It is advised not to use using namespace std;. If there exists an std::multiply with the same signature as of your function (same input-output), the standard one will be called without you noticing it. There are ways to prevent this but not knowing what happened is the problem in the first place. Let the compiler guide you and do not trick yourself.
The flow of the code and the uses of the labels seem complicated. Write code that you will understand, for example, two months later. I suggest breaking seperate functionalities into functions, like readFloat, checkEpsilonValid etc.
Declare variables when they are needed. This way it is easier to follow the code. Also, using meaningful variables instead of two-letter ones improves the readability and you do not even need to comment later.
Finally, be aware that setprecision affects cout throughout the program. It is about whether you care, but for bigger projects, I suggest using printf("%.06f"), or "%.06g", then flush if necessary.
I'm reading Inside The C++ Object Model and find confused about inline function expansion.
In general, each local variable within the inline function must be introduced into the enclosing block of the call
as a uniquely named variable. If the inline function is expanded multiple times within one expression, each
expansion is likely to require its own set of the local variables. If the inline function is expanded multiple
times in discrete statements, however, a single set of the local variables can probably be reused across the
multiple expansions.
Here, what does it mean to expand inline function multiple times in discrete statements and how could that happen? Can anyone raise a concrete example to apply this?
I had some trouble to handle the term discrete statement (especially because it has been emphasized multiple times). I tried to find something like a clear definition (by google) but I couldn't. Thus, I decided to read this literally as one statement (with discrete in the sense of separate).
Denoting a function inline is just a hint to the compiler that the programmer would like to have the function body inserted directly at every "call point" (instead of simply calling the function). Actually, the compiler decides whether the function is really inlined. (It might be even inlined at one point of call but become a function call at another point.) If a macro is used instead of the inline function, the inline requirement would be granted (as macro expansion is actually nothing else than text replacement). Of course, macros have a lot of limitations which inline functions have not. One of them is that inline functions may have local variables.
I made a synthetic example. It's not code "ready for production" but it hopefully helps to illustrate the topic:
#include <iostream>
using namespace std;
inline int absValue(int a)
{
int mB = -a;
return a < 0 ? mB : a;
}
int main()
{
int value;
// use input to prevent compile-time computation
cout << "input: " << flush;
cin >> value;
// multiple usages of absValue()
cout << "value: " << value << endl
<< "absValue(value): "
<< absValue(value)
<< endl
<< "absValue(-value): "
<< absValue(-value)
<< endl;
// done
return 0;
}
The second output statement calls function absValue() multiple times where the call should be inlined. I imagine it like:
// multiple usages of absValue()
cout << "value: " << value << endl
<< "absValue(value): "
<< {
int mB = -(value);
return (value) < 0 ? mB : (value);
}
<< endl
<< "absValue(-value): "
<< {
int mB = -(-value);
return (-value) < 0 ? mB : (-value);
}
<< endl;
There are two occurrences of mB in this statement. On one hand, these are two separate local variables. On the other hand, they may share the same storage on stack as they are used consecutively. (They might not share the same storage if the compiler optimization introduces some kind of code re-ordering which results in interleaving of the first and second expansion of absValue().)
This whole explanation is rather theoretically. Practically, the compiler will hopefully put mB into a register or even optimize most of the code away.
I fiddled a little bit with godbolt to illustrate it further. Finally, I must admit that it proofs essentially my last paragraph above.
I have such simple macro which has two argument:
#define DO_SOMETHING(__X__ , __Y__) \
do{ \
__X__;\
__Y__;\
} while (0);
Here there are three examples of how I use this macro, besides console output:
DO_SOMETHING(cout << "Part 1";); //=> Part1 //NoErr
DO_SOMETHING(cout << "Part 1"; , cout << "Part 2";); //=> Part1 Part2
DO_SOMETHING(cout << "Part 1";, cout << "Part 2";, cout << "Part3";); //=> Part1 Part2 //NoErr
I think it's due to the way comma , is interpreting in macro.
Question: However, I'd like to see a compile-time error for case 1 and 3. How can I achieve it?
PS: I can't use function instead since I need the context! For example the first parameter may be a return; statement.
EDIT: Real macro is not such easy. In fact, we have a repetitive switch-case all over project that we want to have a mechanism to check if we handle are cases in all switches. we could do it by (1) Polymorphism (2) function-call. solution (1) is not applicable since we will have a ultra-huge class with hardly cohesion codes, and solution (2) is not possible because we need Context.
PS: We do need to compiler on both Visual Studio and GCC, as well as xCode environment.
I have this snippet of C++ code from an exam. We are just suppose to write out what the output of the program is, I assumed the output would be '20', but the output is '10'. Why is this?
#define func(x) (x*x)-x
int i=3;
int main() {
cout << func(i+2) << endl;
}
If I put the i+2 in brackets like so:
cout << func( (i+2) ) << endl;
The output is '20' as assumed it would be.
How does C++ process this code that makes it return 10 not 20?
That's just how macros work. It's pure text substitution. So func(i+2) expands as:
(i+2*i+2)-i+2
which is to say:
2*i + 4
This is why typically macros would be written by excessively parenthesizing the arguments:
#define func(x) (((x)*(x))-(x))
But really, this is why you should strongly prefer functions to macros. While parenthesizing the arguments would fix the usage in func(i+2), it still wouldn't fix the usage in func(++i) - which while being a straightforward expression if func were a function is undefined behavior with the macro.
Because the brackets aren't there.
The macro expands to
(i+2*i+2)-i+2
And it all goes wrong from there. An inline function instead of a macro would just work.
Lessons to be learned: (1) Always parenthesise inside macro definitions. (2) DON'T USE MACROS IN C++!
Our project uses a macro to make logging easy and simple in one-line statements, like so:
DEBUG_LOG(TRACE_LOG_LEVEL, "The X value = " << x << ", pointer = " << *x);
The macro translates the 2nd parameter into stringstream arguments, and sends it off to a regular C++ logger. This works great in practice, as it makes multi-parameter logging statements very concise. However, Scott Meyers has said, in Effective C++ 3rd Edition, "You can get all the efficiency of a macro plus all the predictable behavior and type safety of a regular function by using a template for an inline function" (Item 2). I know there are many issues with macro usage in C++ related to predictable behavior, so I'm trying to eliminate as many macros as possible in our code base.
My logging macro is defined similar to:
#define DEBUG_LOG(aLogLevel, aWhat) { \
if (isEnabled(aLogLevel)) { \
std::stringstream outStr; \
outStr<< __FILE__ << "(" << __LINE__ << ") [" << getpid() << "] : " << aWhat; \
logger::log(aLogLevel, outStr.str()); \
}
I've tried several times to rewrite this into something that doesn't use macros, including:
inline void DEBUG_LOG(LogLevel aLogLevel, const std::stringstream& aWhat) {
...
}
And...
template<typename WhatT> inline void DEBUG_LOG(LogLevel aLogLevel, WhatT aWhat) {
... }
To no avail (neither of the above 2 rewrites will compile against our logging code in the 1st example). Any other ideas? Can this be done? Or is it best to just leave it as a macro?
Logging remains one of the few places were you can't completely do away with macros, as you need call-site information (__LINE__, __FILE__, ...) that isn't available otherwise. See also this question.
You can, however, move the logging logic into a seperate function (or object) and provide just the call-site information through a macro. You don't even need a template function for this.
#define DEBUG_LOG(Level, What) \
isEnabled(Level) && scoped_logger(Level, __FILE__, __LINE__).stream() << What
With this, the usage remains the same, which might be a good idea so you don't have to change a load of code. With the &&, you get the same short-curcuit behaviour as you do with your if clause.
Now, the scoped_logger will be a RAII object that will actually log what it gets when it's destroyed, aka in the destructor.
struct scoped_logger
{
scoped_logger(LogLevel level, char const* file, unsigned line)
: _level(level)
{ _ss << file << "(" << line << ") [" << getpid() << "] : "; }
std::stringstream& stream(){ return _ss; }
~scoped_logger(){ logger::log(_level, _ss.str()); }
private:
std::stringstream _ss;
LogLevel _level;
};
Exposing the underlying std::stringstream object saves us the trouble of having to write our own operator<< overloads (which would be silly). The need to actually expose it through a function is important; if the scoped_logger object is a temporary (an rvalue), so is the std::stringstream member and only member overloads of operator<< will be found if we don't somehow transform it to an lvalue (reference). You can read more about this problem here (note that this problem has been fixed in C++11 with rvalue stream inserters). This "transformation" is done by calling a member function that simply returns a normal reference to the stream.
Small live example on Ideone.
No, it is not possible to rewrite this exact macro as a template since you are using operators (<<) in the macro, which can't be passed as a template argument or function argument.
We had the same issue and solved it with a class based approach, using a syntax like
DEBUG_LOG(TRACE_LOG_LEVEL) << "The X value = " << x << ", pointer = " << *x << logger::flush;
This would indeed require to rewrite the code (by using a regular expression) and introduce some class magic, but gives the additional benefit of greater flexibiliy (delayed output, output options per log level (to file or stdout) and things like that).
The problem with converting that particular macro into a function is that things like "The X value = " << x are not valid expressions.
The << operator is left-associative, which means something in the form A << B << C is treated as (A << B) << C. The overloaded insertion operators for iostreams always return a reference to the same stream so you can do more insertions in the same statement. That is, if A is a std::stringstream, since A << B returns A, (A << B) << C; has the same effect as A << B; A << C;.
Now you can pass B << C into a macro just fine. The macro just treats it as a bunch of tokens, and doesn't worry about what they mean until all the substituting is done. At that point, the left-associative rule can kick in. But for any function argument, even if inlined and templated, the compiler needs to figure out what the type of the argument is and how to find its value. If B << C is invalid (because B is neither a stream nor an integer), compiler error. Even if B << C is valid, since function parameters are always evaluated before anything in the invoked function, you'll end up with the behavior A << (B << C), which is not what you want here.
If you're willing to change all the uses of the macro (say, use commas instead of << tokens, or something like #svenihoney's suggestion), there are ways to do something. If not, that macro just can't be treated like a function.
I'd say there's no harm in this macro though, as long as all the programmers who have to use it would understand why on a line starting with DEBUG_LOG, they might see compiler errors relating to std::stringstream and/or logger::log.
If you keep a macro, check out C++ FAQ answers 39.4 and 39.5 for tricks to avoid a few nasty ways macros like this can surprise you.