Constants in C language

Constant value is understandable as non changeable value like PI=3.141592… value in math. Usually you use constants in your programs, but don’t realize that they are constants. For instance:

x=x+3; The number 3 is a constant which will be compiled directly in addition operation. Constants can be character or string. Like in function printf(“Hello World\n”); “Hello World” is a string constant which is placed in program memory and will never changes.

It is usually recommended to declare constants by using identifier with reserved word const:

const int No=44;

By identifying the variable as constant will cause compiler to store this variable in program memory rather than in RAM, thus saving space in RAM. If special functions used, then constants can be also stored in EEPROM memory.

Few words for the numeric constants. Numeric constants can be declared in many ways indicating their base.

  • Decimal integer constants (base 10) consist of one or more digits, 0 through 9, where 0 cannot be used as the first digit.
  • Binary constants (base 2) begin with a 0b or 0B prefix, followed by one or more binary digits (0, 1).
  • Octal constants (base 8) consist of one or more digits 0 through 7, where the first digit is 0.
  • Hexadecimal constants (base 16) begin with a 0x or 0X prefix, followed by a hexadecimal number represented by a combination of digits 0 through 9, and characters A through F.
  • Floating-point constants consist of:
    • an optional sign – or +;
    • an integer part a combination of digits 0 through 9;
    • a period;
    • a fractional part a sequence of digits 0 through 9;
    • an optional exponent e or E, followed by an optionally signed sequence of one or more digits

For example, the following floating-point constant contains both the optional and required parts: +1.15e-12.

Character constant can be represented as character in quotation marks like ‘t’ or as character code like ‘\x74’. Backslash may confuse compiler. Lets say you want to assign backslash as character then you should write like this ‘\\’.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.