C Programming - Const
- Const - Find Output of Program
- Const - Point Out Errors
#include<stdio.h>
#define MAX 128
int main()
{
char mybuf[] = "India";
char yourbuf[] = "BIX";
char *const ptr = mybuf;
*ptr = 'a';
ptr = yourbuf;
return 0;
}
Step 1: char mybuf[] = "India"; The variable mybuff is declared as an array of characters and initialized with string "India".
Step 2: char yourbuf[] = "BIX"; The variable yourbuf is declared as an array of characters and initialized with string "BIX".
Step 3: char *const ptr = mybuf; Here, ptr is a constant pointer, which points at a char.
The value at which ptr it points is not a constant; it will not be an error to modify the pointed character; There will be an error only to modify the pointer itself.
Step 4: *ptr = 'a'; The value of ptr is assigned to 'a'.
Step 5: ptr = yourbuf; Here, we are changing the pointer itself, this will result in the error "cannot modify a const object".
#include<stdio.h>
#define MAX 128
int main()
{
const int max=128;
char array[max];
char string[MAX];
array[0] = string[0] = 'A';
printf("%c %c\n", array[0], string[0]);
return 0;
}
Step 1: A macro named MAX is defined with value 128
Step 2: const int max=128; The constant variable max is declared as an integer data type and it is initialized with value 128.
Step 3: char array[max]; This statement reports an error "constant expression required". Because, we cannot use variable to define the size of array.
To avoid this error, we have to declare the size of an array as static. Eg. char array[10]; or use macro char array[MAX];
Note: The above program will print A A as output in Unix platform.
#include<stdio.h>
#include<stdlib.h>
union employee
{
char name[15];
int age;
float salary;
};
const union employee e1;
int main()
{
strcpy(e1.name, "K");
printf("%s", e1.name);
e1.age=85;
printf("%d", e1.age);
printf("%f", e1.salary);
return 0;
}
#include<stdio.h>
const char *fun();
int main()
{
char *ptr = fun();
return 0;
}
const char *fun()
{
return "Hello";
}
#include<stdio.h>
int main()
{
const int x;
x=128;
printf("%d\n", x);
return 0;
}
A const variable has to be initialized when it is declared. later assigning the value to the const variable will result in an error "Cannot modify the const object".
Hence Option B is correct