Why is empty string transformed to "(null)"? - printf

I have following code sample:
double t_values[FFT_SIZE];
AnsiString prefix;
double multiplier;
AutoScaleData(t_values, FFT_SIZE, prefix, multiplier);
AnsiString str;
str.printf("Voltage [%sV]", prefix);
Pretty simple isn't it?
String str is used as description for numeric values displayed in graph. For value say 0.05 V it is much more comprehensive and intuitive to say instead that "voltage is 50 mV". This is ensured through using proper prefix in this case "m". For values range <1; 1000) there is no need to add any prefix. We can for example say "voltage over this element is 50 volts" and this is perfectly understandable. I have problem that library function printf keeps adding string "(null)" when prefix is empty string for example:
"Voltage [(null)V]"
I haven't seen this type of behaviour anytime before when using Microsoft Visual Studio. Can this behaviour be somehow avoided?

Short Answer:
str.printf("Voltage [%sV]", prefix.c_str());
Detailed Answer:
AnsiString contains a single class member, a char* pointer named Data. When the string is empty, the Data pointer is NULL. The Data pointer resides at the starting memory address of the AnsiString instance.
When calling printf(), its %s specifier is expecting you to pass in a char* pointer, but you are passing in an AnsiString instance instead. That is effectively the same as passing printf() the internal AnsiString::Data pointer directly. In other words, this statement:
str.printf("Voltage [%sV]", prefix);
Is effectively the same as if you had done this instead:
str.printf("Voltage [%sV]", prefix.data());
That is why printf() outputs "(null)". You are passing it a NULL pointer to begin with.
The AnsiString::c_str() method never returns a NULL pointer. If the string is not empty, c_str() returns the AnsiString::Data pointer as-is. Otherwise, it returns a pointer to a static '\0' character instead. Either way, printf() does not receive a NULL pointer in that situation. If the string is empty, it receives a pointer to a 0-length null-terminated string, so it outputs a blank string instead of "(null)".

If is very likely that your variable prefix is NULL. Try this:
str.printf("Voltage [%sV]", prefix == NULL ? "" : prefix);

I managed to do this with following construction:
str.printf("Voltage [%sV]", prefix.c_str());
But i don't understand what is the difference.

Using the Joachim's answer, I've created the following macro (using C):
#define ISNULLSTR(x) (x == NULL ? "" : x)
And I can use it like:
printf("%s", ISNULLSTR(possible_null_text));
Hopefully it will help someone reaching here for the same reason.

Related

How to properly printf float (*)() in objective-c?

I have these two lines of code that which I try to printf on the console, however, in objective-C I get an error saying that: format specifies type 'double' but the argument has type 'float (*)()'
How to properly make this works in Obj-C?
SomeValue = (float (*)())dlsym(someServices, "someMethod");
printf("%f\n", someValue);
Thanks in advance!
someValue in your code is a function pointer, not a value returned from the corresponding function. If you need to print the value returned from that function, simply invoke it:
printf("%f\n", someValue());
// ^^
It goes without saying that you have to NULL-check anything that comes from dlsym.

Different variable type declaration in Golang

Hi I'm just learning Go since the last view days, read some docs and noted that its something about defining struct or interface. Still cant get the difference between
var result []Struct
and
result := Struct{}
Is there particular docs I can refer to?
The result in the first example is a nil slice. The spec says that variables are initialized to their zero values and that zero value of a slice is nil.
The result in the second example is a Struct value. It uses a short variable declaration and composite literal value for a Struct. The second example identical to
var result Struct
Perhaps you meant to write
result := []Struct{}
for the second example. This is a non-nil zero length slice. The expression []Struct{} is a composite literal for an empty slice of Struct.

Exclamation operator?

I'm learning D and have seen a lot of code like this:
ushort x = to!ushort(args[1]);
I assume this casts args[1] to ushort, but what's the difference between this and cast(ushort)?
EDIT: And what other uses does the exclamation mark operator have?
In D,
to!ushort(args[1])
is shorthand for the template instantiation
to!(ushort)(args[1])
and is similar to
to<ushort>(args[1])
in languages like C++/Java/C#.
The exclamation point is to note the fact that it's not a regular argument, but a template argument.
The notation does not use angle brackets because those are ridiculously difficult to parse correctly for a compiler (they make the grammar very context-sensitive), which makes it that much more difficult to implement a correct compiler. See here for more info.
The only other use I know about is just the unary 'not' operation (e.g. false == !true)... I can't think of any other uses at the moment.
Regarding the cast:
cast(ushort) is an unchecked cast, so it won't throw an exception if the value is out of range.
to!ushort() is a checked cast, so it throws an exception if the value is out of range.
The exclamation mark here is not an operator, it is just a token part of the explicit template instantiation syntax (described in detail here).
std.conv.to (docs) is a function template for converting between arbitrary types. It is implemented entirely in the library and has no special support in the language. It has a broader and different scope compared to the cast operator.
The to template takes two type parameters; a "to" type and a "from" type, in that order. In your example, the template is explicitly instantiated with the single type argument ushort for the "to" parameter, and a second type argument string (assuming args comes from the first parameter to main) is automatically inferred from the regular function argument passed to the function (args[1]) as the "from" parameter.
The resulting function takes a string parameter and returns a ushort parsed from that string, or throws an exception if it failed. The cast operator will not attempt this kind of high-level conversion.
Note that if there is more than one explicit template parameter, or that parameter has more than one token in it (ushort is a single keyword token), you must wrap the template parameter list in parentheses:
ushort result;
result = to!(typeof(result))(args[1]);
In this example, typeof, (, result and ) are four separate tokens and the parentheses are thus required.
To answer your last question, the ! token is also used for the unary not operator, unrelated to template instantiations:
bool yes = true;
bool no = !yes; // 'no' is false
You already got two excellent answers by jA_cOp and Merhdad. I just want answer directly to the OP question (what's the difference between this and cast(ushort)?) - The difference is that cast(ushort)args[1] will not work (you cannot cast from a string to an uint just like that), while the to!(type)(param) template knows what to do with the string and how to convert it to the primitive type.

Evaluate if int matches a defined enum type

I have an enum typedef containing several type definitions, eg:
ActionTypeSomething = 1,
ActionTypeSomethingElse = 2
And so on.
So a method I've written evaluates a passed int and then returns a value (for example, a string) accordingly.
(NSString *)evaluatAndReturnProperResult:(int)typeID
NSString *repsonseString;
switch (typeID)
case actionTypeSomething: {
responseString = #"an appropriate string for typeID"
}
...
return responseString;
So my switch evaluates each supported type and returns the correct string.
Now for my question:
I only want to return strings for supported types (i.e., in theory any integer could be passed). If there's no match, I return nil.
Obviously I can do this using exactly the method I already have. But could I (in theory) improve performance by evaluating the passed int to see if it matches any of my defined enum types BEFORE I send it through switch (the switch isn't massive, but I'd still rather just return nil at the beginning of the method if I know there's not going to be a match).
I'm sure this is easy, could someone suggest how to evaluate if my passed integer matches any define enum ActionType before I enter the switch? In this case I'm probably prematurely optimizing, but it's more of a general question about how to do achieve it (not if I should).
You can define 2 more enum values:
typedef enum {
ActionTypeMin = 1,
ActionTypeSomething = 1,
ActionTypeSomethingElse = 2,
ActionTypeMax = 2
} ActionType;
Then check:
typeID >= ActionTypeMin && typeID <= ActionTypeMax
The argument for your method shouldn't be an int, it should ideally be the enum you have defined. This gives you some compile time checking.
If this is not possible then your default case in the switch will handle it just fine - that's what they are designed for.
You are using a TypeDef that's to limit ActionEnum to a set of values, so you shouldn't be using int in your program except for up or downstream communication. Some would say not even then and that you should recive a string and map it to the enum and vice versa.
In terms of getting your strings the usual optimsatiin is
Have an array of strings from ActionType1 to ActionTypeN.
Use the enum as the index to look it up from the array.
The array will also give you the doings to map the string to the enum.
A simple if statement of the enum cast as an integer against teh bound of the array will let you deal gracefully with a bad value, though to me that should throw a big blaring exception.

ComBSTR assignment

I'm confused about COM string assignments. Which of the following string assignment is correct. Why?
CComBSTR str;
.
.
Obj->str = L"" //Option1
OR should it be
Obj->str = CComBSTR(L"") //Option2
What is the reason
A real BSTR is:
temporarily allocated from the COM heap (via SysAllocString() and family)
a data structure in which the string data is preceded by its length, stored in a 32-bit value.
passed as a pointer to the fifth byte of that data structure, where the string data resides.
See the documentation:
MSDN: BSTR
Most functions which accept a BSTR will not crash when passed a BSTR created the simple assignment. This leads to confusion as people observe what seems to be working code from which they infer that a BSTR can be initialized just like any WCHAR *. That inference is incorrect.
Only real BSTRs can be passed to OLE Automation interfaces.
By using the CComBSTR() constructor, which calls SysAllocString(), your code will create a real BSTR. The CComBSTR() destructor will take care of returning the allocated storage to the system via SysFreeString().
If you pass the CComBSTR() to an API which takes ownership, be sure to call the .Detach() method to ensure the BSTR is not freed. BSTRs are not reference counted (unlike COM objects, which are), and therefore an attempt to free a BSTR more than once will crash.
If you use str = CComBSTR(L"") you use the constructor:
CComBSTR( LPCSTR pSrc );
If you use str = L"" you use the assignment operator:
CComBSTR& operator =(LPCSTR pSrc);
They both would initialize the CComBSTR object correctly.
Personally, I'd prefer option 1, because that doesn't require constructing a new CComBSTR object. (Whether their code does so behind the scenes is a different story, of course.)
Option 1 is preferred because it only does one allocation for the string where as option 2 does 2 (not withstanding the creation of a new temporary object for no particular reason). Unlike the bstr_t type in VC++ the ATL one does not do referenced counted strings so it will copy the entire string across.