Answer the question
In order to leave comments, you need to log in
Is it always necessary to use the int type?
Good afternoon. I'm learning C and today I learned that it's not always necessary to use the int type. Let's say if I use small numbers in calculations, then it's better to use the char type, for example. Is it worth using such types or is it better to just int ?
Answer the question
In order to leave comments, you need to log in
Everything depends on the goals. In the vast majority of cases, you can use int and not worry about wasting memory.
It is worth thinking about if there are billions of such variables or resources are very limited.
I would rather think about the possibility of overflow, the result of an operation with variables of a particular type is not always placed in it. This is more important than the mystical economy.
And it is also important that the types in the expression match each other and the programmer's expectation.
Each data type has its own characteristics and limitations. For example, you have a list of up to five items, such as menu items, and each item needs a number or ID. It would be logical to allocate one byte for this field, 0-255 - this will be quite enough. Or, for example, a counter, which can only be positive - it would be logical to use an unsigned type for it. Again, a lot depends on what is considered by this counter. Menu items or entries in the database. So for each task, you should choose the optimal solution.
Whatever you need in a specific situation in a specific program on a specific platform - use this one.
Maybe you need to save memory (under which thread you write the microcontroller) - then byte or something. Or you have hard-coded ints somewhere - why then char ...
Arithmetic with two char operands always performs integer promotion to int. In this regard, using int is at least safer.
if the processor is 32-bit, and all its mathematics with 32-bit numbers, what for your 8-bit chars, the compiler will also make 32-bit ones out of them, and store them in memory as 32-bit ones, filling the remaining bits with zeros
, it will even boolean 32 -it will do bits,
so you should use the type that is native to the processor
, but for 8-bit microcontrollers, yes, there is char native, and if everything that is possible fits into it, then it should be used
and boolean will be 8-bit there
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question