Declare Structure
Lesson 2 of 8 in Coddy's C/C++ Structures course.
To declare a structure, use struct keyword and declare its members inside curly braces.
struct { int num; char letter; }The above structure contains an integer named num and a character named letter.
To use a structure, you need to give it a name, just after the struct keyword:
struct MyStruct { int num; char letter; };In the above example, we declare a structure named MyStruct.
For readability purposes, it's common practice to write a structure like this:
struct MyStruct {
int num;
char letter;
};It's a common convention in both languages to start struct names with an uppercase letter, especially to differentiate them from variable names.
Challenge
EasyYou are given some code (you can peek into it to get ideas for the next lessons).
Declare a structure named Point that will have two float members named x and y (in that order).
Try it yourself
#include <stdio.h>
// Declare the point structure here
int main() {
struct point p1 = {1.5, 2.5};
struct point p2 = {3.2, 4.8};
printf("p1 (%.1f, %.1f)\n", p1.x, p1.y);
printf("p2 (%.1f, %.1f)\n", p2.x, p2.y);
return 0;
};