Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Can I make a calculation with a value outside of the range of my variable?

I'm coding in C and I know the values that can be stored in a uint8_t range from 0 to 255. I want to store a value that is the percentage of MAX_INTENSITY, declared as: #define MAX_INTENSITY 200

Can I do the following: uint8_t my_intensity = (MAX_INTENSITY * percentage) / 100; ?

The result will be 200 or less, but during the calculation, the intermediate result can be superior to 255, e.g. with percentage = 50, MAX_INTENSITY * percentage = 10'000. Can this cause a problem, even if the final result will be 100, o in the range of a uint8_t?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In C, the rules to determine the type used for each intermediary computation are somewhat intricate, but for your particular case quite easy:

The multiplication MAX_INTENSITY * percentage involves an integer constant 200 of type int and a variable percentage. If the type of percentage is int or a smaller type such as uint8_t, this operand will undergo an integer promotion to type int and the result will have type int, then used as an operand for the division by 100, another integer constant with type int, hence a computation with type int and a result of the same type. The result will be converted to the type of the destination, uint8_t, which is performed by take the positive modulo 256, a fully defined operation, especially if percentage is known to be in range 0 to 200.

Therefore, your definition is correct:

uint8_t my_intensity = (MAX_INTENSITY * percentage) / 100;

You might nevertheless consider using type int for this local variable, as there is no benefit in typing it with a smaller type in this context.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda