What is the difference between #define and creating a regular type?

In C / C ++, what is the difference between using #define[and #ifndef #endif] to create values, when you can easily do it with intor std::string[C ++] too?

#ifndef MYVAL
#define MYVAL(500)
#endif

//C++

cout << MYVAL << endl;

//C

printf(MYVAL);

//C++

int MYVAL = 500;
cout << MYVAL << endl;

//C
int MYVAL = 500;
printf(MYVAL);
+4
source share
6 answers

Before I go into history, here we briefly understand the difference between the two.

Variables are, well, variables. They occupy a place in the compiled program, and if you do not mark them const(this is a much later version than macros), they are mutable.

, , . . . , . , ( ).

, . , , , , -.

++. :

  • . , - ( -), const, "" - MYVAR 500.
  • . , . , , . .
  • #define -
    • ( , , , , ),
    • C,
    • DEBUG, - . , -, DEBUG. ( , .)

, , - .

+6

. #define "", . C ++ .

+12

, (#) . .

, , , .

C/++ 2- . - , . - , .

, , . , - "" . , , .

, . #define MYVAL(500) MYVAL 500, , , .., .

+5

#define -, , :

#define the_answer 42
/// ...

int the_answer = /* oops! */
+2

:

a) #define MYVAL 500

. . , .

b) int MYVAL = 500;

, , .. . , , ..

, (#if, #endif blocks)

:

#define MYVAL 500

int main() {
    int MYVAL = 10; // illegal, gets preprocessed as int 500 = 10;
}

:

int MYVAL = 500

int main() {
    int MYVAL = 10; // legal, MYVAL now references local variable, ::MYVAL is the global variable
}
+1

All Articles