goto statement between methods C++ - c++

I am running some code to quickly test. I know I would almost never use a goto statement, but I need to test if certain parts of a method work at a certain period of time, and I'm just curious. I know that I can jump between lines of code in visual by right clicking in a method and say go to cursor, or a goto statement inside of that method, but what if I want to test certain code at a certain time, In a different method? If I wanted to see if it would work in a given situation without recreating that line of code? I read http://www.tutorialspoint.com/cplusplus/cpp_goto_statement.htm about goto statements, but when trying it in between class methods, it won't recognize the statement. I guess I could try method calls and goto's, but I'm really curious for curiosity sake for one, and two it isn't like I'm using the code. I just need to test something quickly.

when trying it in between class methods, it won't recognize the statement.
That's right. You need to define a label in order to use goto statement. The scope of label definitions is local to functions, so jumping to a label in a different function is not allowed.
It wouldn't be of much help anyway, because in order to get into a function you need more context than just the line position in the code: among other things, you need to provide the state for all parameters, all variables, loop counters, and so on.
On top of that, there are restrictions even on using goto within the same function: you cannot jump over a variable definition and use that variable after that.

Related

Tools to refactor names of types, functions and variables?

struct Foo{
Bar get(){
}
}
auto f = Foo();
f.get();
For example you decide that get was a very poor choice for a name but you have already used it in many different files and manually changing ever occurrence is very annoying.
You also can't really make a global substitution because other types may also have a method called get.
Is there anything for D to help refactor names for types, functions, variables etc?
Here's how I do it:
Change the name in the definition
Recompile
Go to the first error line reported and replace old with new
Goto 2
That's semi-manual, but I find it to be pretty easy and it goes quickly because the compiler error message will bring you right to where you need to be, and most editors can read those error messages well enough to dump you on the correct line, then it is a simple matter of telling it to repeat the last replacement again. (In my vim setup with my hotkeys, I hit F4 for next error message, then dot for repeat last change until it is done. Even a function with a hundred uses can be changed reliably* in a couple minutes.)
You could probably write a script that handles 90% of cases automatically too by just looking for ": Error: " in the compiler's output, extracting the file/line number, and running a plain text replace there. If the word shows up only once and outside a string literal, you can automatically replace it, and if not, ask the user to handle the remaining 10% of cases manually.
But I think it is easy enough to do with my editor hotkeys that I've never bothered trying to script it.
The one case this doesn't catch is if there's another function with the same name that might still compile. That should never happen if you do this change in isolation, because an ambiguous name wouldn't compile without it.
In that case, you could probably do a three-step compiler-assisted change:
Make sure your code compiles before. Then add #disable to the thing you want to rename.
Compile. Every place it complains about it being unusable for being disabled, do the find/replace.
Remove #disable and rename the definition. Recompile again to make sure there's nothing you missed like child classes (the compiler will then complain "method foo does not override any function" so they stand right out too.
So yeah, it isn't fully automated, but just changing it and having the compiler errors help find what's left is good enough for me.
Some limited refactoring support can be found in major IDE plugins like Mono-D or VisualD. I remember that Brian Schott had plans to add similar functionality to his dfix tool by adding dependency on dsymbol but it doesn't seem implemented yet.
Not, however, that all such options are indeed of a very limited robustness right now. This is because figuring out the fully qualified name of any given symbol is very complex task in D, one that requires full semantics analysis to be done 100% correctly. Think about local imports, templates, function overloading, mixins and how it all affects identifying the symbol.
In the long run it is quite certain that we need to wait before reference D compiler frontend becomes available as a library to implement such refactoring tool in clean and truly reliable way.
A good find all feature can be better than a bad refactoring which, as mentioned previously, requires semantic.
Personally I have a find all feature in Coedit which displays the context of a match and works on all the project sources.
It's fast to process the results.

Removal of unused or redundant code [duplicate]

This question already has answers here:
Listing Unused Symbols
(2 answers)
Closed 7 years ago.
How do I detect function definitions which are never getting called and delete them from the file and then save it?
Suppose I have only 1 CPP file as of now, which has a main() function and many other function definitions (function definition can also be inside main() ). If I were to write a program to parse this CPP file and check whether a function is getting called or not and delete if it is not getting called then what is(are) the way(s) to do it?
There are few ways that come to mind:
I would find out line numbers of beginning and end of main(). I can do it by maintaining a stack of opening and closing braces { and }.
Anything after main would be function definition. Then I can parse for function definitions. To do this I can parse it the following way:
< string >< open paren >< comma separated string(s) for arguments >< closing paren >
Once I have all the names of such functions as described in (2), I can make a map with its names as key and value as a bool, indicating whether a function is getting called once or not.
Finally parse the file once again to check for any calls for functions with their name as in this map. The function call can be from within main or from some other function. The value for the key (i.e. the function name) could be flagged according to whether a function is getting called or not.
I feel I have complicated my logic and it could be done in a smarter way. With the above logic it would be hard to find all the corner cases (there would be many). Also, there could be function pointers to make parsing logic difficult. If that's not enough, the function pointers could be typedefed too.
How do I go about designing my program? Are a map (to maintain filenames) and stack (to maintain braces) the right data structures or is there anything else more suitable to deal with it?
Note: I am not looking for any tool to do this. Nor do I want to use any library (if it exists to make things easy).
I think you should not try to build a C++ parser from scratch, becuse of other said in comments that is really hard. IMHO, you'd better start from CLang libraries, than can do the low-level parsing for you and work directly with the abstract syntax tree.
You could even use crange as an example of how to use them to produce a cross reference table.
Alternatively, you could directly use GNU global, because its gtags command directly generates definition and reference databases that you have to analyse.
IMHO those two ways would be simpler than creating a C++ parser from scratch.
The simplest approach for doing it yourself I can think of is:
Write a minimal parser that can identify functions. It just needs to detect the start and ending line of a function.
Programmatically comment out the first function, save to a temp file.
Try to compile the file by invoking the complier.
Check if there are compile errors, if yes, the function is called, if not, it is unused.
Continue with the next function.
This is a comment, rather than an answer, but I post it here because it's too long for a comment space.
There are lots of issues you should consider. First of all, you should not assume that main() is a first function in a source file.
Even if it is, there should be some functions header declarations before the main() so that the compiler can recognize their invocation in main.
Next, function's opening and closing brace needn't be in separate lines, they also needn't be the only characters in their lines. Generally, almost whole C++ code can be put in a single line!
Furthermore, functions can differ with parameters' types while having the same name (overloading), so you can't recognize which function is called if you don't parse the whole code down to the parameters' types. And even more: you will have to perform type lists matching with standard convertions/casts, possibly considering inline constructors calls. Of course you should not forget default parameters. Google for resolving overloaded function call, for example see an outline here
Additionally, there may be chains of unused functions. For example if a() calls b() and b() calls c() and d(), but a() itself is not called, then the whole four is unused, even though there exist 'calls' to b(), c() and d().
There is also a possibility that functions are called through a pointer, in which case you may be unable to find a call. Example:
int (*testfun)(int) = whattotest ? TestFun1 : TestFun2; // no call
int testResult = testfun(paramToTest); // unknown function called
Finally the code can be pretty obfuscated with #defineā€“s.
Conclusion: you'll probably have to write your own C++ compiler (except the machine code generator) to achieve your goal.
This is a very rough idea and I doubt it's very efficient but maybe it can help you get started. First traverse the file once, picking out any function names (I'm not entirely sure how you would do this). But once you have those names, traverse the file again, looking for the function name anywhere in the file, inside main and other functions too. If you find more than 1 instance it means that the function is being called and should be kept.

Verilog: Why is there a if(0) if if(1) is always true?

I have the verilog always block as below:
always # (a)
begin
if(1) begin
..
end
if(0) begin
...
end
end
Does if(1) mean that this statement is executed all the time once the always block is triggered?
Then what is the point having if(0)? When is it executed?
Note: This is a legacy code, I'm not the owner of it.
I don't know if it's the intent here, but that sort of construct allows you to write source code that contains several different blocks of code, and to quickly change which one(s) you want in the source by changing which conditional has the 1.
For example, they might contain two different ways of implementing the same thing, and this makes it easier to switch back and forth if you need to test which one gives better performance.
Or, it might be about how many options you want to include in the source.
Or, sometimes, it's a form of version control and lets you keep old code around until you're sure you don't need it anymore.
Someone probably added this to disable a whole block of code. Basically as if it is inside a block comment. This is particularly useful if a piece of code already contains block comments. But it's a bit hacky too, and I wouldn't use it in production code, and certainly not without adding a comment.

File is getting really big need to separate data into another file but also need to use private variables. How can I achieve this correctly?

So I have a huge (legacy) file, call it HUGE.cxx. I'm adding new feature, but the file is getting even more big. I tried to create different classes for different jobs, but for some task I need to access the private variables. Here is a rough draft of what is going on
//HUGE.h
class Huge{
NewFeature object;
//...more stuff
};
//HUGE.cxx
Huge::Huge(){
//imagine object keeps track of id->func callback
object.on('uniqueID1', boost::bind(&HUGE::onID1Clicked,this));
}
void Huge::onID1Clicked()const{ return satisfiesSomeCondition(); }
//called internally when user right clicks
void Huge::createPopup()const{
for itr = object.begin to end
callback = itr->second;
//if satisfies condition add to popupmenu
if(callback()) addToPopupMenu( itr->first );
}
//event handler
void Huge::event(id){
//oh uniqueID1 was clicked as a menu item in right click
case 'uniqueID1': doSpecificFunctionality(); break;
}
so you see, I have some dependencies going there, but the file is so big and so are my changes. Do you have any advice on further separating out into more files. I know I can add a friend declaration to Huge file and add another class, but wanted to avoid that option if possible.
Sounds like you actually need a major refactor, separating concerns into their proper places.
But, to solve your immediate problem, there's no particular reason why all of Huge needs to be defined in Huge.cxx. You can split the function definitions into separate files, as long as every function is defined somewhere.
You might end up with:
Huge.h
Huge-private.cxx
Huge-public.cxx
Or however it makes sense to split your code.
As long as all the .cxx files include HUGE.h, and all the used functions are declared there (which should be the case), you can split up the implementation in as many .cxx files as you want. You could even put each function into its own file.
To call a function, the compiler only needs to see the prototype from HUGE.h. Later, when all the compiled files are linked together, the linker will combine the code from the different object files as appropriate.
Serious advice: Learn about refactoring (http://refactoring.com) and design patterns.
Without seeing the whole thing, it is hard or impossible to tell you something really specific. You probably need an arsenal of refactoring ammunition. For some parts, extracting methods and merging common functionality is the right thing; for other parts, dependency inversion may be the tool of choice.
Beyond some critical mass of mud, a (clean) rewrite might be the sanest and most profitable thing to do: Begin with defining what the input and the expected output is (during that, write tests).

let the user use a function in c++ [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Dynamic source code in C++
is it possible to let the user type in a function and then run that function without using a lot of if's or a huge switch?
It is not possible to execute arbitrary c++ code in your program, since you than need a c++ compiler inside your program. But you could try to embed Python to your program. Boost python makes this relatively easy. The user can than write a python function that is executed and can interact with the classes and functions of your program. You need to make your functions explicitely visible to python.
What ever a user types in will be text, or a string. The only way I know to have it get mapped to a function is to use if/else or switch statements. That or the cringe inducing option of mapping each of your functions to a UI widget.
The end of the story, is it's your code. You have to write, and live with it. Just be careful, your program may be wildly successful, and you may not write code anymore, and then someone else will have to maintain your code. So be nice to the maintenance programmer who may follow you, and write code that isn't too tricky to figure out.
I assume you want something like eval from php.
You can try to play with command design pattern, but I doubt it will be an easy task. Basically you need to write simple C++ interpreter.
What type of function do you mean? A C++ function? If so, then you will have to either (1)interpret it or (2)compile and execute it. Interpretation would be the more likely choice here. I'm not sure if there are libraries out there already to do this but I'd assume there are.
If you don't like mega-if's or huge switches, you may be SoL on any solution for anything ever, but then again there is seldom one perfect way to do things. Consider looking in to various logic structures and algorithms to see how to do something that would normally be the job of a 23-case switch could be done another way. Like I said initially, however, sometimes you really do just need a million nested if's to do what you want to.
No, in C++ this is not possible. C++ is a compiled language. When the program runs, the compiler doesn't need to be accessible, or even installed on the machine that runs the program.
If you want to do this in C++, you need to write your own interpreter that parses whatever the user enters.
Here is my best idea, but it is a tad memory intensive.
First, create a class, lets call it MyFuncPtr to store a union of several different types of pointers to functions and an integer to tell which type it is. Overload the () operator to call the function stored with a variable length argument list. Make sure to include some sort of run-time argument checking.
Finally create a map of strings to MyFuncPtrs. Store your functions in this map along with their names. Then all you need to do is feed the name into the [] command to get a function that can be easily called. Templates could probably be used to aid in the making of MyFuncPtr instances.
This would be the easiest if it were plain C functions and no name mangling is performed on the symbols (use extern "C" { ... })
With some platform-specific code you can get the address of a function by its name. Then you cast the address as a function pointer which you can use to call the function.
On windows you must be using GetProcAddress and dlsym on Posix compliant platforms.