In C and C++, what is the correct keyword used to define a user-defined structure type that groups related data members under a single name?

Difficulty: Easy

Correct Answer: struct

Explanation:


Introduction / Context:
Structures provide a way to create composite types by grouping variables under one logical unit. This mechanism is central to modeling records, points, and other multi-field entities. Using the correct keyword ensures the compiler recognizes the declaration and generates the proper layout in memory.


Given Data / Assumptions:

  • The language is standard C or C++.
  • We intend to define a new type with several named fields.
  • No typedefs, classes, or unions are implied beyond the basic structure keyword.


Concept / Approach:
The reserved word struct initiates a structure definition. For example: struct Person { std::string name; int age; }; creates a type named Person with two members. In C++, struct and class are similar in capability, but the default access for struct members is public, whereas for class it is private. Tokens like stru, stt, or the word structure are not C or C++ keywords and will cause compile-time errors if used in place of struct.


Step-by-Step Solution:
Choose the keyword struct to begin the type definition.Provide a tag name and a brace-enclosed list of members.Optionally, create variables or use typedef/using to introduce aliases.Use the new type to declare variables that group related fields together.


Verification / Alternative check:
Compile a simple program with struct Point { int x; int y; }; Point p; p.x = 3; p.y = 4; and observe successful compilation and execution. Replacing struct with a nonkeyword token will fail to compile.


Why Other Options Are Wrong:

  • stru and stt are not language keywords.
  • structure is English prose, not a reserved identifier in C or C++.
  • None of the above is incorrect because struct is correct.


Common Pitfalls:
Confusing struct and class default access. In C++, either may be used to define rich types; choose based on intent and coding style.


Final Answer:
struct.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion