Created
June 21, 2014 13:26
-
-
Save w495/5947818e882b93cfea1c to your computer and use it in GitHub Desktop.
Пример для иллюстрации употребления const с указателями. Компилировать -std=c99 -Wall -pedantic
This file contains hidden or 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<stdio.h> | |
#include<stdlib.h> | |
#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* i1 = malloc(sizeof(int)); | |
int* i2 = malloc(sizeof(int)); | |
int* i3 = malloc(sizeof(int)); | |
*i1 = 100; | |
*i2 = 200; | |
*i3 = 300; | |
LOG("INITS :"); VARLOG(i1); VARLOG(i2); VARLOG(i3); LOG("\n"); | |
const int* p1 = i1; | |
int* const p2 = i2; | |
const int* const p3 = i3; | |
LOG("WORKERS :"); VARLOG(p1); VARLOG(p2); VARLOG(p3); LOG("\n"); | |
// --------------------------------------------------------------- | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// *p1 = 101; | |
/// ✅ Все ок! | |
p1 = i3; | |
LOG("p1 <-- i3;"); VARLOG(p1); LOG("\n"); | |
// --------------------------------------------------------------- | |
/// ✅ Все ок! | |
*p2 = 201; | |
LOG("*p2 <-- 201;"); VARLOG(p2); LOG("\n"); | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// p2 = i3; | |
// --------------------------------------------------------------- | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// *p3 = 301; | |
/// ✘ Ошибка! | |
/// ✘ Попытка изменить константное значение. | |
// p3 = i3; | |
// --------------------------------------------------------------- | |
free(i1); | |
free(i2); | |
free(i3); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
✒ Инициализируем все
i
и смотрим на них.✒ Инициализируем все
p
и смотрим на них.✒ Присвоили
p1 = i3
. Уp1
поменялся адрес.✒ Присвоили
*p2 = 201
. Уp2
нельзя поменять адрес.