Created
June 21, 2014 13:55
-
-
Save w495/9e50ad2b9cb54759600d to your computer and use it in GitHub Desktop.
Пример для иллюстрации употребления const с указателями. Компилировать g++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<cstdio> | |
#define LOG_HELPER(fmt, ...) \ | |
fprintf( \ | |
stderr, \ | |
"\033[32mLOG:\033[0m " \ | |
"\033[33m%s\033[0m " \ | |
"\033[36m%s\033[0m " \ | |
"[\033[1m%d\033[0m] : " fmt "%s", \ | |
__FILE__, \ | |
__FUNCTION__, \ | |
__LINE__, \ | |
__VA_ARGS__ \ | |
) | |
#define LOG(...) \ | |
LOG_HELPER(__VA_ARGS__, "\n") | |
#define VARLOG(x) \ | |
LOG("%s(\033[31m%p\033[0m) = %d", #x, (void*)x, *x) | |
int main(){ | |
int* i = new int(111); | |
const int* p1 = new int(100); | |
int* const p2 = new int(200); | |
const int* const p3 = new int(300); | |
LOG("WORKERS :"); | |
VARLOG(p1); | |
VARLOG(p2); | |
VARLOG(p3); | |
// --------------------------------------------------------------- | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// *p1 = 101; | |
/// ✅ Все ок! | |
p1 = i; | |
LOG("p1 <-- i;"); | |
VARLOG(p1); | |
// --------------------------------------------------------------- | |
/// ✅ Все ок! | |
*p2 = 201; | |
LOG("*p2 <-- 201;"); | |
VARLOG(p2); | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// p2 = i; | |
// --------------------------------------------------------------- | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// *p3 = 301; | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// p3 = i; | |
// --------------------------------------------------------------- | |
if(p1) | |
delete(p1); | |
if(p2) | |
delete(p2); | |
if(p3) | |
delete(p3); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment