Can I temporarily disable random / srand in c++? - c++

I have a very large codebase that uses srand and rand that I need to debug. The random executions make debugging difficult, since bugs occur randomly too. Is there any way to temporary make the library execute deterministically so I can debug the code?

If you can add a file in the include chain, you can put this in that file:
#define rand() (4)
Not very pretty, but could help.
reference

There is no standard way to disable srand. In some implementations you can redefine it to do nothing and it will work, but that's an ORD violation:
extern "C" void srand(unsigned) noexcept {
// Nothing
}
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
srand((unsigned)time(0));
printf("%d\n", rand());
}
It works in GCC in my testing and prints the same number every time. You probably can use it to debug your code but it's surely not appropriate for production use.

Related

How can I implement a fallback function when some function is missing(at compile time)?

My goal is:
if pthread_setname_np is defined in glibc, we will use glibc's version.
otherwise, we will use a fallback function pthread_setname_np which actually do nothing to prevent compile errors.
This need to be done at compile time.
So I write the following codes
#include <cstdio>
#include <pthread.h>
__attribute__((weak)) int pthread_setname_np(pthread_t thread, const char *name) { printf("foo\n"); return 0; }
int main() {
pthread_setname_np(pthread_self(), "bar");
}
IMO, if I run g++ test_free_bsd.cpp -o test_free_bsd -lpthread, since the symbol is already defined in pthread, so the compile will not link my self-defined symbol.
However, the program still prints out "foo", which means it actually uses my weak symbol.
Then it occurred to me that my self-defined pthread_setname_np is in the same unit with main, there are no linking. So I changed to the following
// g++ test_free_bsd.cpp test_free_bsd2.cpp -o test_free_bsd -lpthread
// test_free_bsd.cpp
#include <cstdio>
#include <pthread.h>
int main() {
pthread_setname_np(pthread_self(), "bar");
}
// test_free_bsd2.cpp
#include <cstdio>
#include <pthread.h>
__attribute__((weak)) int pthread_setname_np(pthread_t thread, const char *name) { printf("foo\n"); return 0; }
However, the program still prints out foo. So I am lost here. IMO, in test_free_bsd.cpp, it will link pthread_setname_np in glibc, rather than in test_free_bsd2.cpp which is a weak symbol.
=== UPDATE ===
Why I wan to do this? There is a fallback in codes of Clickhouse. I am using these codes in my project, though I don't know why they are here. However, I don't want to change its behavior. I only want these lines to take effects only we are sure the glibc we linked to do not has pthread_setname_np.
On FreeBSD pthread_setname_np seems to exists, it is defined in pthread_setname_np.h. I don't know why you get a linker error (I can't test it.)
However, you should be able to use #ifndef _GNU_SOURCE around your pthread_setname_np to only define it if it isn't defined by pthread.h.

Why can't I include the standard algorithm library after defining 'epsilon' in C++?

When I include the algorithm library before defining epsilon, the following code compiles:
#include <iostream>
#include <algorithm>
#define epsilon 0.00001
int main() {
std::cout << epsilon;
return 0;
}
When I switch them around, it doesn't:
#include <iostream>
#define epsilon 0.00001
#include <algorithm>
int main() {
std::cout << epsilon;
return 0;
}
It gives the following error 19 times:
epsilon_algorithm.cpp:3:17: error: expected unqualified-id before numeric constant
3 | #define epsilon 0.00001
|
On http://www.cplusplus.com/reference/algorithm/ and https://en.cppreference.com/w/cpp/algorithm there is no mention of anything named 'epsilon'. I know I can avoid the issue by simply always including <algorithm> before I define epsilon, I want to know what causes this error to broaden my understanding of C++ and prevent these types of errors in the future.
I compile with MinGW (32 bit, installed a few weeks ago) in an updated Windows 10 (64 bit) environment.
Standard library headers are allowed to include any other standard library header.
It's possible that <algorithm> includes <limits> and there exists std::numeric_limits::epsilon() there. And of course macros ignore namespaces and classes, so it would try to declare a function called 0.00001.
Don't use macros. Use C++ constants:
constexpr double epsilon = 0.00001;
And if you absolutely need macro, always define them after all includes. Defining them before makes your code very brittle - any change in those headers in the future might blow up your code with cryptic compiler errors.
Don't define macros in header files, for the same reason.
Prefer very localized macros when possible - define them where needed and #undef after you are done. This way they won't leak to the outside (although you can still inadvertently override an existing macro).

Delay in Dev C++

I have come across to a problem while coding in C++ on Dev C++ compiler. I want to delay my statement to some milliseconds, but the problem is dev doesnt support the dos.h header file and so its contents as well. I had an alternative way for using it with the help of for loop but i aint got its proper syntax in my mind to use it properly. I wish, you folks, might be able to resolve the problem for me. Thanks in Advance..
#include <dos.h>
int main(){
delay(1000)
cout << "Hello"
return 0;
Tell me another alternative way for this please.
C++ has < thread >
< thread > has "std::this_thread::sleep_for(...)"
Example illustrating the (...)
std::this_thread::sleep_for(100ms);
The ms of 100 ms comes from
using namespace std::chrono_literals; // support suffixes like 100ms, 2s, 30 us
Probably you also need to include < chrono >
Use the header chrono and thread
#include <iostream>
#include <thread>
#include <chrono>
using namespace std::this_thread;
using namespace std::chrono;
sleep_for(nanoseconds(10));
sleep_until(system_clock::now() + seconds(1));
You can change the nanoseconds part to seconds or keep it at nanoseconds, and the number beside it is the amount of that unit that you can change to any number.
Use empty for loop
for example:
for(int i=0; i<10000; i++);
Change upper bound according to your need.

srand(time(NULL)) "Function 'srand' could not be resolved."

I have been trying to debug this problem for a while and quite honestly, I just can't see what I'm doing wrong.
Why is there a syntax error?
#include <iostream>;
#include <time.h>;
#include <stdio.h>;
#include <stdlib.h>;
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
The error I'm getting is,
"Function 'srand' could not be resolved."
I'm well aware now that I don't need the semi-colons after 'include' statements
I'm using Eclipse CDT along with MinGW as my compiler
How I resolved the problem:
It had to do with the MinGW compiler I was using. Switching over to Visual Studio solved the problem.
; at the end of the #include directives are the problem in your code. #include directives don't need (wrong to place indeed) semicolons at the end unlike C++ statements.
[Warning] extra tokens at end of #include directive [enabled by default]
It seems any character after > in the directive causes this error/warning.
#include<iostream>a //error
Change to this:
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
int main(){
cout<<"Hello Main";
}
EDIT:
Regarding the linker issue:
One suggestion is C++ expects types to be explicitly casted between types (more than C). So, use a cast to convert time_t which is returned by the time to unsigned int which is the input parameter type of srand. (And of course this might not be the problem with linker error)
Instead of using stdlib.h, try using <cstdlib>, try if it helps. Because it uses namespace.
Apart from that, I have seen this snippet here. Use that pattern if it helps.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //use current time as seed for random generator
int random_variable = rand();
cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
there is already question in SO check if that helps Eclipse Method could not be resolved in a simple program C++
Never use time() to initialize srand()..
EDIT:
Now it seems many people got this kind of problem. I found a question How do I fix Eclipse CDT Error “Function 'isdigit' could not be resolved. He is facing the same problem. The asker suggested a work around to this in his question edit.
Quoted from that question:
I now believe this to be a Code Analysis problem. A better solution is
to edit the Code Analysis options to make "Function could not be
resolved" be a warning instead of an error. That way you can see the
warnings in Problems view, but continue to work. If the function is
REALLY missing, the compiler will tell you! I also have a new theory,
that the problem is with the Code Analyzer following symlinks, because
all of the "missing" functions are in symlinked include files. Would
love any input on this theory.
Hope that points to solve the problem.
; should not be there after #include.
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include files shoule not end with ;

cout weird output

When I try using cout, it outputs a random number rather then the sentence I want. There is not compiler error, the program runs fine.
Here is my code:
//question.h
#ifndef _QUESTION_H_
#define _QUESTION_H_
using namespace std;
int first()
{
cout<<"question \n";
return 0;
}
#endif
//main.cpp
#include <iostream>
#include "question.h"
using namespace std;
void main(){
cout<<""<<first<<""<<endl;
cin.ignore();
cin.get();
}
I'm fairly new to writing my own header files, so I'm not sure if I did something wrong with that or if there's a problem with visual studio.
You're printing the address of the function. You need to call it:
cout<<""<<first()<<""<<endl;
^^
As mentioned in the comments, this doesn't have to output what you expect, either. The order in which arguments to functions (and that is just a bunch of function calls) is unspecified, so your function output could be in any position the compiler chooses. To fix this, put separate statements:
cout<<"";
cout<<first(); //evaluated, so output inside first() printed before return value
cout<<""<<endl;
It might not matter with the empty strings, but it will when you replace those with something visible.
Also, don't use void main. Use int main() or int main(int, char**) (see here). Don't use using namespace std;, especially in headers, as std has a lot of crap in it that is pulled in with that statement, leading to easy and confusing conflicts (see here). Finally, choose a name that does not conflict with identifiers reserved for the implementation as your include guard.
You are printing the address of the function first rather than calling it. But changing the function call won't fix your problem all by itself, because first writes to cout internally and then returns a number, which will be printed, which doesn't appear to be what you want.
If you want first to act like an <iomanip> thingie you have to jump through a few more hoops -- read that header to see how it's done.
Use cout<<""<<first()<<""<<endl; you need to actually call the function, not print its address