Debugging function parameters' value in C++ - c++

I'm coming from scripting languages where this js possible, but I'm not sure if this is possible in C++. I'm working with an external module, and it uses a function, which parameters are not correct, so I tried to check them, but is not as simple as in JavaScript.
To check a parameter value, how can I do it? A simple cout gives me errors about types, and the same if I try to convert them to strings.
Is possible see the parameter value as in JS using a console.log(fooParameter); or something similar?
Thank's advanced!

You can try to use breakpoints in your IDE in order to pause the program when callstack reaches that point and see variables.
You can also overload the << operator in order to write to std::cout your parameter type if it's not a predefined one (string, int, etc).

c++ is an explicitly typed language, so you should have full control over what type is being passed.
However, you can print the variable type during runtime with:
#include <typeinfo>
// …
std::cout << typeid(fooParameter).name() << '\n';
Hope this helps!

Related

Using std::cout on STM32 microcontroller

I managed to use printf() on my STM32 (CortexM7) compiling under C++, by defining functions like _write and _read and so on.
But I wanted to use std::cout instead of printf. However including <iostream> yields like 300 errors.
Do you know what has to be done to use cout with custom char printing functions?
Compiler used G++ 6.2.
I have found partial solution. You can make class (even name it cout) and overload operator << for different types and inside execute printf() with proper format string. Maybe not most efficient but for UART is ok.
So I don't need answer anymore, but if someone knows, then for curiosity you can post it.

c++ how to process the argu which uncertain type?

There's a web api which output json format:
{"ret":0}
c++ program could get the value of "ret", and it's a INT type.
but if modify the api, output to this:
{"ret":"0"}
c++ program runs error.
what if the value of "ret" is uncertain type, maybe INT or maybe STRING?
is there a way to process the uncertain type value in c++?
No, C++ is a statically-typed language. It's my opinion that you should code against the datatypes of the API which should not change. It is commonly accepted that if the API chagnges, then the code calling that API has to change as well.
You could just use Regex for different cases.
Like checking if there are two " around your input

Setting a Breakpoint in GDB

I have a function that returns a pointer:
static void *find_fit(size_t asize);
I would like to set a breakpoint in gdb, but when I type this function name, I get one of these errors:
break *find_fit
Function "*find_fit" not defined
or
break find_fit
Function "find_fit" not defined
I can easily set break point on a function that returns something other than a pointer, but when the function does return a pointer, gdb doesn't seem to want to break on it.
Anybody see what is going on? Thanks!
It sounds like for some reason, gdb isn't handling C++ name mangling correctly. Normally you don't have to touch anything for this to work. You can try show language. Typically it's set to auto. You can also try manually setting it with set language c++.
To test, you can just type
b 'find<tab>
(that's the tab character, not the characters "<tab>") and it should try to autocomplete the name of the function for you. In C++ you need the argument types to know the function, but that doesn't 100% fit with what you're seeing because if you give gdb a function name without arguments, it'll usually do the right thing or prompt you for which version of a function you want. You aren't seeing either of those.

directly calling from what user inputs and Is there a concept of generating a function at run time?

Is there a way out to call a function directly from the what the user inputs ?
For example : If the user inputs greet the function named greet is called.
I don't want any cases or comparison for the call to generate.
#include <iostream>
#include<string>
using namespace std;
void nameOfTheFunction(); // prototype
int main() {
string nameOfTheFunction;
getline(cin,nameOfTheFunction); // enter the name of Function
string newString = nameOfTheFunction + "()"; // !!!
cout << newString;
// now call the function nameOfTheFunction
}
void nameOfTheFunction() {
cout << "hello";
}
And is there a concept of generating the function at run time ?
You mean run time function generation ??
NO.
But you can use a map if you already know which all strings a user might give as input (i.e you are limiting the inputs).
For the above you can probably use std::map &lt std::string, boost::function &lt... &gt &gt
Check boost::function HERE
In short, no this isn't possible. Names in C++ get turned into memory offsets (addresses), and then the names are discarded**. At runtime C++ has no knowledge of the function or method names it's actually running.
** If debug symbols are compiled in, then the symbols are there, but impractical to get access to.
Generating a function at runtime has a lot of drawbacks (if it is possible at all) and there is generally no good reason to do it in a language like C++. You should leave that to scripting languages (like Perl or Python), many offer a eval() function that can interpret a string like script code and execute it.
If you really, really need to do have something like eval() in a compiled language such as C++, you have a few options:
Define your own scripting language and write a parser/interpreter for it (lots of work)
Define a very simple imperative or math language that can be easily parsed and evaluated using well-known design patterns (like Interpreter)
Use an existing scripting language that can be easily integrated into your code through a library (example: Lua)
Stuff the strings of code you want to execute at runtime through an external interpreter or compiler and execute them through the operating system or load them into your program using dlopen/LoadLibrary/etc.
(3.) is probably the easiest and best approach. If you want to keep external dependencies to a minimum or if you need direct access to functionality and state inside your main program, I suggest you should go for (2.) Note that you can have callbacks into your own code in that case, so calling native functions from the script is not a problem. See here for a tutorial
If you can opt for a language like Java or C#, there's also the option to use the compiler built into the runtime itself. Have a look here for how to do this in Java

Counterpart of PHP's isset() in C/C++

PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.
Can we build similar feature for C/C++ (some kind of symbol table lookup)?
I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe).
You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously explicitly defined. There really is no such thing as an "unset" variable in C++.
Even if you say "int var;" and do not initialize it, the variable has a value, usually garbage, but it's still "set" in the PHP sense.
The closes I suppose would be the preprocessor's #ifdef and #ifndef which only checks to see if you've defined a variable using #define. But in my experience this is mostly used for omitting or adding code based on flags. For example:
// code code code
#ifdef DEBUG
// debug only code that will not be included in final product.
#endif
// more code more code
You can define DEBUG using #define to determine whether to include "DEBUG" code now.
Perhaps telling a bit more about what you're trying to do with the C++ equivalent of isset will give you a better idea of how to go about doing it "The C++ Way".
There is no direct means of doing this in the language. However, it is possible to do this sort of thing by using a map such as the following:
typedef std::map<std::string, int> variables_type;
variables_type variables;
variables["var"] = 1;
if(variables.find("jon") == variables.end())
std::cout << "variable, \"jon\" not set\n";
In order to make this a variable like those used in PHP or javascript, the implementation would need to use some sort of variant type.
Not really. You can't dynamically create variables (though you can dynamically create storage with malloc() et al, or new et al. in C++) in C. I suppose dynamically loaded libraries blur the picture, but even there, the way you establish whether the variable exists is by looking up its name. If the name is not there, then, short of running a compiler to create a dynamically loaded module and then loading it, you are probably stuck. The concept really doesn't apply to C or C++.
As said in other answers, in C++ variables are never undefined. However, variables can be uninitialised, in which case their contents are not specified in the language standard (and implemented by most compilers to be whatever happened to be stored at that memory location).
Normally a compiler offers a flag to detect possibly uninitialised variables, and will generate a warning if this is enabled.
Another usage of isset could be to deal with different code. Remember that C++ is a statically compiled language, and attempting to redefine a symbol will result in a compile time error, removing the need for isset.
Finally, what you might be looking for is a null pointer. For that, just use a simple comparison:
int * x(getFoo());
if (x) {
cout << "Foo has a result." << endl;
} else {
cout << "Foo returns null." << endl;
}
Well there is always Boost.Optional
http://www.boost.org/doc/libs/1_36_0/libs/optional/doc/html/index.html
which should almost do what you want.
Short answer: NO
Standard followup question: What problem are you really trying to solve?
You've got to separate two things here: variable declaration and variable contents.
As said in other answers, unlike PHP, C++ doesn't allow a variable to be used before it's declared.
But apart from that, it can be uninitialized.
I think the PHP isset function tries to find out if a variable has a usable value. In C++, this corresponds best to a pointer being NULL or valid.
The closest thing I can think of is to use pointers rather than real variables. Then you can check fro NULL.
However, it does seem like you're solving wrong problem for the language, or using wrong language to solve your problem.