Scanf resets constant variable

Viewed 57

I'm messing with bit operators in C and I have this piece of code:

#include <stdio.h>
#include <stdlib.h>
#include "binario.h"

int main() {
    const unsigned char idade = 28;
    unsigned char temp1 = 0, temp2 = 0;
    
    printf("Trabalhando bit a bit\n");
    printf("---------------------\n\n");
    
    printf("Aqui farei alguns testes usando operadores bit a bit.\n");
    printf("Estarei usando minha idade como referencia.\n");
    printf("Em decimal: %u\n", idade);
    printf("Em binario: ");
    transformaBinario(idade);
    printf("\nEm caractere: %c\n\n", idade);
    
    printf("Agora, usarei o operador bit a bit \"~\" com a minha idade.\n");
    temp1 = ~idade;
    printf("Em decimal: %u\n", temp1);
    printf("Em binario: ");
    transformaBinario(temp1);
    printf("\nEm caractere: %c\n\n", temp1);
    
    printf("Agora, usarei o operador bit a bit \"&\" com um valor inserido.\n");
    printf("Digite um numero entre 0 e 255: ");

    scanf("%u", &temp2);
    /*FACING PROBLEMS IN THIS SCANF ABOVE!*/

    printf("O valor digitado corresponde, em decimal, a: %u\n", temp2);
    printf("O valor digitado corresponde, em caractere, a: %c\n", temp2);
    printf("O valor %u em binario, corresponde a: ", temp2);
    transformaBinario(temp2);
    printf("\nO valor %u em binario, corresponde a: ", idade);
    transformaBinario(idade);
}

binario.h is some library that just made some decimal to binary conversion. The problem here is that until that scanf, my constant "idade" has a value of 28. After that, it just got reset to 0. I have no problems at all with that temp2 variable... it's just my constant that erased to 0. Can you please help me?

1 Answers

Instead of %u, you need to use %c for unsigned char.

Related