Skip to content

Instantly share code, notes, and snippets.

@w495
Created June 21, 2014 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w495/5947818e882b93cfea1c to your computer and use it in GitHub Desktop.
Save w495/5947818e882b93cfea1c to your computer and use it in GitHub Desktop.
Пример для иллюстрации употребления const с указателями. Компилировать -std=c99 -Wall -pedantic
#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;
}
@w495
Copy link
Author

w495 commented Jun 21, 2014

✒ Инициализируем все i и смотрим на них.

LOG: ./test.c main [33] : i1(0x1b66010) = 100
LOG: ./test.c main [33] : i2(0x1b66030) = 200
LOG: ./test.c main [33] : i3(0x1b66050) = 300

✒ Инициализируем все p и смотрим на них.

LOG: ./test.c main [39] : p1(0x1b66010) = 100
LOG: ./test.c main [39] : p2(0x1b66030) = 200
LOG: ./test.c main [39] : p3(0x1b66050) = 300

✒ Присвоили p1 = i3. У p1 поменялся адрес.

LOG: ./test.c main [51] : p1(0x1b66050) = 300

✒ Присвоили *p2 = 201. У p2 нельзя поменять адрес.

LOG: ./test.c main [59] : p2(0x1b66030) = 201 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment