0

I am learning C language. I was reading to declare constants. What is the difference between

#define PI 3.1415927

and

float const PI = 3.1415927;

Thanks.

user2656997
  • 103
  • 1
  • 1
  • 6

1 Answers1

2
  1. #define is text replacement. All occurrences of PI in your code will be replaced by 3.1415927 before compilation.

  2. const creates read-only variables. That means you can't assign to them, but you still can't use them as e.g. case labels, because they're not true constants.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • Note: This is rather an incomplete list of differences, a more complete list can be found in the duplicate questions answers. – hyde Oct 09 '15 at 10:20
  • What's missing (apart from the `#ifdef` stuff)? – melpomene Oct 09 '15 at 10:21
  • Well, taking address (possible with const variable), converting to string (possible with preprosessor), differences in using as array size (variable creates a VLA, technically), from the top my head. – hyde Oct 09 '15 at 10:23
  • @hyde Taking address is possible with variables in general (covered by #2) and not possible with literals (covered by #1). String conversion is possible with all macro arguments; I don't see how that applies. Why would you use `float PI` as the size of an array? – melpomene Oct 09 '15 at 10:25