0

I am wondering why the results turn out to be 100, 8, 1 in the output. 010 doesn't even make any sense that it is not 2 in binary digits. Am I missing something?

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    int code[3];
    code[0] = 100;
    code[1] = 010;
    code[2] = 001;
    printf("%d\n", code[0]);
    printf("%d\n", code[1]);
    printf("%d\n", code[2]);
}
Jacob G.
  • 28,856
  • 5
  • 62
  • 116

1 Answers1

1

100, 010 and 001 are not binary literals. 100 is a decimal literal; 010 and 001 are octal (base 8) literals. If you are using gcc there is an extension to support binary literals by using the prefix 0b, as in

code[0] = 0b100; // evaluates to 4
meat
  • 609
  • 3
  • 8
  • is it an extension? or is it fully-supported as specified in the [standard](https://timsong-cpp.github.io/cppwp/lex.literal#lex.icon-1)? – Joseph D. Jun 27 '18 at 04:14
  • It is an extension, e.g. [6.63 Binary Constants using the ‘0b’ Prefix](https://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html) (but I get your point `:)` And see: [syntax - Why doesn't C have binary literals?](https://stackoverflow.com/questions/18244726/why-doesnt-c-have-binary-literals) – David C. Rankin Jun 27 '18 at 04:15
  • @DavidC.Rankin, sorry I thought this is a C++ question? – Joseph D. Jun 27 '18 at 04:19
  • 1
    @codekaizer - crud -- I'm getting old and senile -- it is a C++ question, and you are correct, but note from C++14 forward according to [cppreference.com - integer literal](https://en.cppreference.com/w/cpp/language/integer_literal) – David C. Rankin Jun 27 '18 at 05:05