I'm working with a function that uses bitwise operations with the length of a file: fpos_t flen;
When I try casting it to an int or char, or attempt on arithmetic operation on it, it fails with the following compilation error:
error: aggregate value used where an integer was expected
You're misusing that type. First, it doesn't represent a length. It represents a position. Second, it's only meant to use in a call to fsetpos. You're not meant to do arithmetic on it because it doesn't necessarily represent a numeric type. It contains whatever information your library needs to be able to perform an fsetpos operation. In your library's implementation, fpos_t appears to be an aggregate type, such as a struct. (You can check the definition in the header files to be sure, but don't rely on whatever you discover there; it's liable to differ on other platforms or in future versions of your standard library.)
As for your next step, consider asking a more direct question about how to solve whatever problem you were working on when you came up with the idea to do bitwise operations on a fpos_t.
I was getting the same error when i was trying to do this:
char aux = (char)flen & 15, where flen was fpos_t.
I found a solution here: http://dsmarkchen.blogspot.com.br/2008/08/fpost.html .
It should be:
char aux = flen.__pos & 15.
It sounds like you want to work with current file position as an integer. If so, you'll probably want to use ftell/fseek (or their 64-bit brethren), rather than fgetpos/fsetpos. Both serve analogous operations, but ftell/fseek work with integral values, while fgetpos/fsetpos work with an intentionally-abstract structure.
Related
As far as I could find, the width of the bool type is implementation-defined. But are there any fixed-width boolean types, or should I stick to, for e.g., a uint8_t to represent a fixed-width bool?
[EDIT]
I made this python script that auto-generates a C++ class which can hold the variables I want to be able to send between a micro controller and my computer. The way it works is that it also keeps two arrays holding a pointer to each one of these variables and the sizeof each one of them. This gives me the necessary information to easily serialize and deserialize each one of these variables. For this to work however the sizeof, endianness, etc of the variable types have to be the same on both sides since I'm using the same generated code on both sides.
I don't know if this will be a problem yet, but I don't expect it to be. I have already worked with this (32bit ARM) chip before and haven't had problems sending integer and float types in the past. However it will be a few days until I'm back and can try booleans out on the chip. This might be a bigger issue later, since this code might be reused on other chips later.
So my question is. Is there a fixed width bool type defined in the standard libraries or should I just use a uint8_t to represent the boolean?
There is not. Just use uint8_t if you need to be sure of the size. Any integer type can easily be treated as boolean in C-related languages. See https://stackoverflow.com/a/4897859/1105015 for a lengthy discussion of how bool's size is not guaranteed by the standard to be any specific value.
Type safety is a big thing in C++. Variables of different types which don't support implicit conversions can not be set to be equal.
How this safety check is performed?
In addition to the variable itself, is there some information about type stored for that variable?
The variable itself doesn't contain any information about what it contains. Instead C++ uses its compile step to perform a wide array of verification steps to ensure that everything will work correctly during run time.
Put simply if I have the following function:
double convert(int32_t num)
{
return static_cast<double>(num);
}
It compiles into a procedure which takes its one and only parameter and performs a 32-bit integer to 64-bit floating point conversion. If you gave it a 32-bit floating point number it would do the incorrect thing.
However the type system ensures that anyone who calls convert supplies a 32-bit integer (note the compiler may insert a conversion on your behalf in some cases, but the function only ever sees a 32-bit integer) and thus there is no need for a run-time check that what you supplied is actually a 32-bit integer.
The type system does exist at compile time of course and is tracked quite carefully. Take the following example:
int32_t x = 12;
double y = convert(x);
The compilers view of this includes that x is an int32_t, convert takes a int32_t and returns a double and y is a double. Since those all line up no conversion is necessary and it compiles successfully. In contrast:
char* x = "12";
double y = convert(x);
Doesn't compile because char * is not the same (and is not convertible) to int32_t.
C++ is designed as a compiled language. Which means that whatever checks are required by the language specification are performed at compilation time by the compiler. Everything that is necessary for such checks is stored by the compiler in compiler's inner data structures. These data structures exists only during compilation.
Once the C++ code is successfully compiled into executable code, all checks are done. Nothing is stored anymore. Nothing is checked anymore.
In other words, type-safety checks in C++ language are static.
The only exception from this principle is the functionality of dynamic_cast, which can perform certain run-time (dynamic) type checks. For that storing some run-time type information (RTTI) is indeed necessary. The same data is used for run-time type identification through typeid. But this is a separate topic, which does not really override the fact that general type checking in C++ is static in nature.
I'm working with some embedded code and I am writing something new from scratch so I am preferring to stick with the uint8_t, int8_t and so on types.
However, when porting a function:
void functionName(char *data)
to:
void functionName(int8_t *data)
I get the compiler warning "converts between pointers to integer types with different sign" when passing a literal string to the function. ( i.e. when calling functionName("put this text in"); ).
Now, I understand why this happens and these lines are only debug however I wonder what people feel is the most appropriate way of handling this, short of typecasting every literal string. I don't feel that blanket typecasting in any safer in practice than using potentially ambiguous types like "char".
You seem to be doing the wrong thing, here.
Characters are not defined by C as being 8-bit integers, so why would you ever choose to use int8_t or uint8_t to represent character data, unless you are working with UTF-8?
For C's string literals, their type is pointer to char, and that's not at all guaranteed to be 8-bit.
Also it's not defined if it's signed or unsigned, so just use const char * for string literals.
To answer your addendum (the original question was nicely answered by #unwind). I think it mostly depends on the context. If you are working with text i.e. string literals you have to use const char* or char* because the compiler will convert the characters accordingly. Short of writing your own string implementation you are probably stuck with whatever the compiler provides to you. However, the moment you have to interact with someone/something outside of your CPU context e.g. network, serial, etc. you have to have control over the exact size (which I suppose is where your question stems from). In this case I would suggest writing functions to convert strings or any data-type for that matter to uint8_t buffers for serialized sending (or receiving).
const char* my_string = "foo bar!";
uint8_t buffer* = string2sendbuffer(my_string);
my_send(buffer, destination);
The string2buffer function would know everything there is to know about putting characters in a buffer. For example it might know that you have to encode each char into two buffer elements using big-endian byte ordering. This function is most certainly platform dependent but encapsulates all this platform dependence so you would gain a lot of flexibility.
The same goes for every other complex data-type. For everything else (where the compiler does not have that strong an opinion) I would advise on using the (u)intX_t types provided by stdint.h (which should be portable).
It is implementation-defined whether the type char is signed or unsigned. It looks like you are using an environment where is it unsigned.
So, you can either use uint8_t or stick with char, whenever you are dealing with characters.
When creating custom typedefs for integers, is it possible for compiler to warn when you when using a default numeric type?
For example,
typedef int_fast32_t kint;
int_fast32_t test=0;//Would be ok
kint test=0; //Would be ok
int test=0; //Would throw a warning or error
We're converting a large project and the default int size on platform is 32767 which is causing some issues. This warning would warn a user to not use ints in the code.
If possible, it would be great if this would work on GCC and VC++2012.
I'm reasonably sure gcc has no such option, and I'd be surprised if VC did.
I suggest writing a program that detects references to predefined types in source code, and invoking that tool automatically as part of your build process. It would probably suffice to search for certain keywords.
Be sure you limit this to your own source files; predefined and third-party headers are likely to make extensive use of predefined types.
But I wouldn't make the prohibition absolute. There are a number of standard library functions that use predefined types. For example, in c = getchar() it makes no sense to declare c as anything other than int. And there's no problem for something like for (int i = 0; i <= 100; i ++) ...
Ideally, the goal should be to use predefined types properly. The language has never guaranteed that an int can exceed 32767. (But "proper" use is difficult or impossible to verify automatically.)
I'd approach this by doing a replace-all first and then documenting this thoroughly.
You can use a preprocessor directive:
#define int use kint instead
Note that technically this is undefined behavior and you'll run into trouble if you do this definition before including third-party headers.
I would recommend to make bulk replacement int -> old_int_t at the very beginning of your porting. This way you can continue modifying your code without facing major restrictions and at the same time have access to all places that are not yet updated.
Eventually, at the end of your work, all occurencies of old_int_t should go away.
Even if one could somehow undefine the keyword int, that would do nothing to prevent usage of that type, since there are many cases where the compiler will end up using that type. Beyond the obvious cases of integer literals, there are some more subtle cases involving integer promotion. For example, if int happens to be 64 bits, operations between two variables of type uint32_t will be performed using type int rather than uint32_t. As nice as it would be to be able to specify that some variables represent numbers (which should be eagerly promoted when practical) while others represent members of a wrapping algebraic ring (which should not be promoted), I know of no facility to do such a thing. Consequently, int is unavoidable.
I'm using boost::any in combination with boost::any_cast<> to write some framework code which should take a set of arguments, almost like a function call, and convert them into an array of boost::any types.
So far everything has been working great, except in places where it is hard to predict if the number the caller gives me is going to be signed or unsigned. A lot of code in our existing product (windows based) uses DWORD and BYTE data types for local variables so if one of those variables is used, I get unsigned type. However if a constant is hardcoded, the most likely it'll be a simple number in which case it will be signed.
Since I can't predict if I should do any_cast<int> or any_cast<unsigned int>, 50% of the time my code that reads the boost::any array will fail.
Does anyone know if there's a way to just a number out of boost::any regardless if original type was signed or unsigned?
There isn't a way; boost::any does the simplest form of type-erasure, where the type must match exactly. You can write your own boost::any-like class that supports the additional features you want. I've previously demonstrated how this can be done.
Failing that, you can:
Have two code paths, one for each sign. (Switch to signed path if any_cast<unsigned T> throws.)
Try unsigned, and if that throws, try signed and cast, use a single code path.
Just let the unsigned any_cast throw if it's signed, and force the user to cope.
However, each of these isn't really that good. Do you really need boost::any? Perhaps you want boost::variant instead, if you're expecting a certain list of types.