Short Syntax
Lesson 4 of 8 in Coddy's C/C++ Structures course.
It's also possible to assign values to members of a structure variable at declaration time, in a single line.
Insert the values in a comma-separated list inside curly braces {}, the order is important!
#include <iostream>
#include <string>
struct Student {
int roll_number;
std::string name;
float marks;
};
int main() {
Student student1 = {101, "Alice", 85.5};
std::cout << "Roll Number: " << student1.roll_number << std::endl;
std::cout << "Name: " << student1.name << std::endl;
std::cout << "Marks: " << student1.marks << std::endl;
return 0;
}Or in C, (note that you don't to use the strcpy method)
#include <stdio.h>
struct Student {
int roll_number;
char name[50];
float marks;
};
int main() {
struct Student student1 = {101, "Alice", 85.5};
printf("Roll Number: %d\nName: %s\nMarks: %.2f\n", student1.roll_number, student1.name, student1.marks);
return 0;
}Challenge
EasyCreate a structure Employee that will hold the name (string), the id (int) and the salary (float) of the employee.
After that, initialize three employees and print their values in the format:
ID: {id}, Name: {name}, Salary: {salary}Try it yourself
#include <stdio.h>
#include <string.h>
int main() {
// Write code here
return 0;
};