0

Why does C not accept 08 and 09 as an integer? Are there ways that I could still validate the 08 and 09 as an integer?

int main(){
    int a;
    scanf("%i", &a);

    if (a== 8 || a==08){
        printf("Octagon");
    }
    else if (a== 9 || a==09){
        printf("Nonagon");
    }

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    What are you trying to do with `08`, and how would it be different from `8`? – interjay Jun 09 '21 at 17:17
  • 1
    by the way you missed `&` , should be `scanf("%i", &a);` – Sudipto Jun 09 '21 at 17:17
  • 1
    What exactly are you expecting it to do? `08`, if octal weren't a thing, would be equivalent to `8`, so I'm not sure why you were testing for both; you parsed it from a string, so it's no longer a string, and has no concept of leading zeroes anymore. – ShadowRanger Jun 09 '21 at 17:17
  • 1
    C++ but close enough: https://stackoverflow.com/questions/26568200/what-is-special-about-numbers-starting-with-zero –  Jun 09 '21 at 17:19
  • I'm considering the possibility that the user inputs 08, not 8. – CodeBeginner Jun 09 '21 at 17:19
  • 2
    @CodeBeginner: If the user input `08`, since you used `%i` as the `scanf` format code, it wouldn't work correctly anyway; `%i` looks for and handles prefixes like `0` (meaning octal) and `0x`/`0X` (hex) so it would try to parse it as octal and fail (and you'd never know, because you're not checking the return value from `scanf`; it'll have whatever was in `a` originally). If you want to handle strict decimal inputs, use `%d`, and the leading zeroes will be ignored (you'll get `8` no matter how many zeroes they prefix it with, because there is no such thing as an `int` with a *value* of `08`). – ShadowRanger Jun 09 '21 at 17:20
  • 1
    You're comparing the numeric value, not the string representation. – Barmar Jun 09 '21 at 17:20
  • 1
    Unrelated note: Always, *always* check the return value from `scanf`. It might be zero or EOF. You can only use the value of `a` in your program if `scanf` returned exactly `1`. – Zan Lynx Jun 09 '21 at 17:23

1 Answers1

1

I think that if you look carefully at the compiler error, it will mention that you have specified an invalid octal constant.

This is because any number that begins with a 0 (that isn't followed by an x) is interpreted as an octal constant. Valid digits for octal constants are 0-7, with 8 and 9 being invalid.

The simple solution is to remove the leading zeroes.

Note that you're comparing an int with the values of eight and nine. Even if the user input a number with a leading zero, the binary representation of the integer value does not store that fact. Looking for a leading zero might be useful if you were looking at a string rather than an integer.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39