int listenPort()
{
//if (server)
//{
// return server->port();
//}
//std::cout << server->port() << std::endl;
//return 0;
//add below 2 lines only to make it work right under Realease.
//std::fstream f("Z:/fsfasjlfjal.txt");
//f.close();
if (_listenPort != -1)
{
return _listenPort;
}
return 0;
}
I have one function named listenPort, variable _listenPort has been set to -1 in construct function, I want to check its value. When it changes return it or return 0.
I use Visual Studio 2010 to compile the code, DEBUG everything is OK. But when I change to Release(/O2), function always return 0. I tried add two lines code: fstream open and close. Now it seems everything is right.
But this solution is ugly, I just open and close some file. What should I do? Thanks.
One not recommended solution is to make replace int _listenPort; with volatile int _listenPort;. Read this to understand why this solution is not recommended.
A good solution would use synchronized writing and reading of _listenPort.
Or As I suggested before move definitions of class to a different file. This way, compiler won't inline your code and function will return expected value.
You're probably trying to run a debugger on an optimised (/O2) code and set breakpoints in your function. This is not going to work. Compiler is free to change order of your code as it sees fit, provided that the outcome of the code is the same as if it were untouched.
If you really want to test some values with optimised code, you need to log the values somewhere (a file) or print them out in the console.
Related
I've been attempting to figure out this bug for about an hour now. It's probably a really obvious syntax thing I'm overlooking. This is my first C++ project, and I don't have a good handle on the structure of the language.
Here's my header file:
#pragma once
#include <vector>
class BoardState
{
private:
std::vector<int> numbers;
int SIZE;
public:
BoardState();
std::vector<int> getState();
bool isZero();
};
And here's the implementation, in a separate file:
#include "BoardState.h"
BoardState::BoardState(){
SIZE = 4;
numbers.push_back(1);
numbers.push_back(3);
numbers.push_back(5);
numbers.push_back(7);
}
std::vector<int> BoardState::getState() { return numbers; }
bool BoardState::isZero() {
for (int i = 0; i < numbers.size(); i++) {
if (numbers[i] != 0) { return false; }
}
return true;
}
This code is really simple, so I have no clue what could be going wrong to produce the errors. However, on every method call, push_back and size, I am getting errors, saying that class "std::vector<int, allocator>" has no member "method_name_here".
My background is Java, so my first thought was that I wasn't able to call these methods because numbers is not initialized. However, any attempt I made to initialize numbers in the header file resulted in an error as well. I tried std::vector<int> numbers = { 1,3,5,7 };, I tried std::vector<int> numbers(4,0);, I even tried creating an array and constructing the vector from that. Not only did all those attempts cause errors, they also didn't fix the method calls either.
What am I missing? Do I need to initialize the vector, or is what I have in the header file enough? Any advice would be helpful here, since I can't find anything online about similar errors. I've even copy-pasted code from StackOverflow answers about similar problems, and that produced errors as well.
EDIT: I've pared down the code as much as possible while keeping the error:
#include <vector>
class BoardState
{
std::vector<int> numbers;
BoardState() { numbers.push_back(1); }
int getSize() {
int i = numbers.size();
return i;
}
};
On the line numbers.push_back(1);, my compiler underlines the token "push_back", and highlighting it reads:
class "std::vector<int, allocator>" has no member "push_back"
On the line int i = numbers.size();, the token "size" is underlined, and the error reads:
class "std::vector<int, allocator>" has no member "size"
I still have no clue what's going on.
Edit 2: Put the method calls into a constructor and a function. This changed the error message associated with push_back().
Edit 3: I have discovered something very disconcerting. This code works perfectly fine in a different compiler. I copy-pasted in the exact code from Edit 1 and it ran with no issues. I think the problem must be with Visual Studio rather than the actual code. Thank you all for helping me out with this. I think I'm just going to switch to a different compiler and hope for the best.
Edit 4: Just to prove to pm100 that my code is exactly as I've said, here's a screenshot from visual studio.
Here it is.
Aside from the main method, this is character-for-character what I've put in this question. I have a guess as to why this doesn't work, though. I modified my version of Visual Studio 2019 to run .386 assembly code for a college class. While I think I followed the guide to do that without affecting anything else, it may have screwed up parts of the C++ compiler.
I suggest that you could select Tools->Import and Export Settings->Reset all settings-> Visual C++ to restore the default settings.
If it does not work, you could reinstall VS.
I'm getting errors in my program between two (theoretically) consecutive lines of code, and have no idea what could cause this.
My whole code is huge, so here's the basics;
int playRoom(std::string currentRoom = "Storage_room", std::string entryDoor = "NULL"){
log("Starting playRoom()");
// code to play the level
// includes setting up box2d world
// and playing the level
if(playerWantsRestart){
log("Restart level");
return playRoom(savedData.roomName, savedData.entryDoor);
}
log("Leaving playRoom()");
return 0;
}
int main( int argc, char* args[] ){
// Set up SDL etc..
playRoom();
log("Back in main()");
// Close SDL
return 0;
}
If I never use the restart option, everything is fine.
If I do use it, the program exits with status 3 and the log file reads:
Starting playRoom()
Restart level
Starting playRoom()
Leaving playRoom()
So the error appears to be in "return 0;"?? I don't think status 3 is an overflow, and it's only recursed (?) once anyway, so...
I'm using Codeblocks 12.11, compiling with GNU GCC. Any help or ideas would be great!
int playRoom(std::string currentRoom = "Storage_room", std::string entryDoor = "NULL")
Why are you using int's? I would use Boolean.
Either way read this.
You are calling two different types of methods not sure if they updated java to include this syntactic sugar yet. I've been out of the loop but.
playRoom();
This function should have a set currentRoom and an entryDoor in the method by default.
Then overload it with.
playRoom(string currentRoom , string entryDoor);
Try removing the return statement from the if condition.
Recently, I was reviewing some code I maintain and I noticed a practice different than what I am used to. As a result, I'm wondering which method to use when performing an early return in a function.
Here's some example:
Version 1:
int MyFunction(int* ptr)
{
if(!ptr) { // oh no, NULL pointer!
return -1; // what was the caller doing? :(
}
// other code goes here to do work on the pointer
// ...
return 0; // we did it!
}
Version 2:
int MyFunction(int* ptr)
{
if(!ptr) { // oh no, NULL pointer!
return -1; // what was the caller doing? :(
} else { // explicitly show that this only gets call when if statement fails
// other code goes here to do work on the pointer
// ...
return 0; // hooray!
}
}
As a result, I'm wondering which is considered the "best practice" for those of you who have endured (and survived) many code reviews. I know each effectively does the same thing, but does the "else" add much in terms of readability and clarity? Thanks for the help.
The else would only add clarity if the else clause is short, a few lines of code at best. And if you have several initial conditions you want to check, the source gets cluttered very quickly.
The only time I would use an else if it is a small function with a small else, meaning less than about 10 source lines, and there are no other initial checks to make.
In some cases I have used a single loop so that a series of initial checks can use a break to leave.
do {
...
} while (0);
I am loathe to use a goto which is practically guaranteed to get at least one true believer of goto less programming up in arms.
So much would depend on any code standards of your organization. I tend to like minimalism so I use the first version you provide without the else.
I might also do something like the following in a smaller function say less than 20 or 30 lines:
int MyFunction(int* ptr)
{
int iRetStatus = -1; // we have an error condition
if (ptr) { // good pointer
// stuff to do in this function
iRetStatus = 0;
}
return iRetStatus; // we did it!
}
The only problem with returns in the body of the function is that sometimes people scanning the function do not realize that there is a return. In small functions where everything can be pretty much seen on a single screen, the chance of missing a return is pretty small. However for large functions, returns in the middle can be missed especially large complex functions that have gone through several maintenance cycles and had a lot of cruft and work arounds put into them.
Sun Studio 12.1 prints the warning
Warning: The last statement should return a value.
frequently for functions like that:
int f()
{
/* some code that may return */
// if we end up here, something is broken
throw std::runtime_error("Error ...");
}
It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like
// Silence a compiler warning
return 42;
at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.
What is the recommended way to silence such a warning?
Can you reorganize the code in the function in such a way (hopefully more logical as well) that the normal path happens at the end of the function so that a return can be used, and the exceptional path happens earlier, NOT as the last statement?
EDIT: If reorganizing the function really doesn't make sense, you can always just put a dummy return 0; with a comment. It's better to squelch the warning that way than more globally.
If you really want to quiet the warning permanently, you can use #pragma error_messages (off, wnoretvalue) but note that the warning really is useful most of the time so I absolutely don't suggest turning it off. You can use the on version of the pragma to re-enable the warning after the function, but the compiler will still emit the warning if your function is ever inlined. If you put the function in its own source file and use the pragma that should shush the warning relatively safely though, since it can't affect other translation units.
Another really wacky possibility is to switch to g++. Unless you're compiling for SPARC g++ may actually generate better code than Sun studio.
I find it a perfect spot for abort(). You should never end there, according to you, so something like:
UNREACHABLE("message")
which expands into:
#ifdef NDEBUG
#define UNREACHABLE(Message_) abort();
#else
#define UNREACHABLE(Message_) assert(0 && Message_);
#endif
Looks appropriate
Since you know the exception will be systematically called, why don't you simply return a 0?
Perhaps encapsulate the contents in a do { } while (false); construct:
int my_function()
{
int result = DEFAULT_VALUE;
do
{
result = /*...*/
// Whatever
if (error)
{
throw std::runtime_error("Error ...");
}
} while (false);
return result;
}
The idea is for normal operation to set the result value then let the execution flow to the end or use a break to jump to the return statement.
I don't know of a "recommended" way to deal with it, but to answer your question about coping with more complex types, what about:
ComplexType foo()
{
...
throw std::runtime( "Error..." );
return *(ComplexType*)(0);
}
This would then work with any return type. I realise it looks evil, but its there just to silence the warning. As you say, this code will never be executed, and it may even be optimised out.
I have a unit test project based on UnitTest++. I usually put a breakpoint to the last line of the code so that the I can inspect the console when one of the tests fails:
n = UnitTest::RunAllTests();
if ( n != 0 )
{
// place breakpoint here
return n;
}
return n;
But I have to reinsert it each time I check-out the code anew from SVN. Is it possible to
somewhat place the breakpoint by the compiler?:
n = UnitTest::RunAllTests();
if ( n != 0 )
{
// place breakpoint here
#ifdef __MSVC__
#!!!$$$??___BREAKPOINT;
#endif
return n;
}
return n;
Use the __debugbreak() intrinsic(requires the inclusion of <intrin.h>).
Using __debugbreak() is preferable to directly writing __asm { int 3 } since inline assembly is not permitted when compiling code for the x64 architecture.
And for the record, on Linux and Mac, with GCC, I'm using __builtin_trap().
DebugBreak(void)
From Winbase.h.
MSDN
You could use this in C or C++
__asm
{
int 3
}
If you are using VC6 (yes, outdated but still in use in some places/projects), DebugBreak() will work but you may end up in some obscure location deep withing Windows DLLs, from which you have to walk the stack up back into your code.
That's why I'm using ASSERT() in MFC or assert() in "standard" code.
Your example would work like this:
n = UnitTest::RunAllTests();
ASSERT(n == 0);
//assert(n == 0);
return n;
If you don't need a result and want it just for debugging, you can also do
if(0 != UnitTest::RunAllTests())
{
ASSERT(FALSE);
//assert(false);
}
How about using a Debug or Trace method to output the console info. That may be a better approach than relying on breakpoints.
How often do you check out the project from SVN? This is typically something I only do once per project, or when I rebuild my PC.
If you also checkin the project files, the breakpoints should be stored in the project files.
I think it is in the .suo file. You could also put that under SVN control if you wanted, though I prefer not to.