can anyone tell the output of following code and also explain it

#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 %d %f", e1.name, e1.age, e1.salary);
    return 0;
}

Dani AI

Generated

Short answer: the behavior you see is not guaranteed. was right to call this undefined behavior; ’s observation that it “works” on one machine is just a manifestation of undefined behavior on that particular toolchain.

Why: the object was declared const at file scope, so the compiler and optimizer are allowed to assume it will never be modified. Writing into it at runtime (for example, via a library function that expects a char *) violates the language rules and therefore invokes undefined behavior. A compiler will often warn when you pass a const array to a function expecting a non-const char * (see the strcpy signature) but it may still generate code that performs the write. The runtime result depends on details such as endianness, type sizes and whether the object was placed in writable memory or in a read-only segment. See the C library and function docs for the prototype and qualifier rules: strcpy.

Union note: only one union member is the active value at a time; reading a different member reinterprets the stored bytes and is implementation-dependent, so the shown age and salary outputs will vary by platform. See the language rules on unions: unions in C.

Practical fixes:

  • If the value should be constant, initialize it at definition (so it is a proper const object).
  • If you need to write at runtime, remove const.
  • If you need to keep all fields valid simultaneously, use a struct instead of a union.
    Enable warnings (-Wall -Wextra) and run UB sanitizers to catch this class of errors. For rules on initialization and static zero-initialization, see C initialization.
Member Avatar for Member #957352

you can't initialize the const variable after its declaration. Declaraing union as constant has no sense because union is bascially used to make it's use again and again. in line 14, you are making changes in a const variable so which is a error here. thnks.

sir but it is working

Member Avatar for Member #957352

yes, it will work as it is undefined behaviour. you are trying to do a thing which is undefined so it is possible that it may work. thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.