Menu
Coddy logo textTech

Sintassi breve

Lezione 4 di 8 del corso Strutture in C/C++ di Coddy.

È anche possibile assegnare valori ai membri di una variabile struttura al momento della dichiarazione, in un'unica riga.

Inserisci i valori in un elenco separato da virgole tra parentesi graffe {}; l'ordine è importante!

#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;
}

Oppure in C (nota che non devi usare il metodo strcpy)

#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 icon

Sfida

Facile

Crea una struttura Employee che contenga il nome (stringa), l'id (int) e lo stipendio (float) del dipendente.

Dopodiché, inizializza tre dipendenti e stampa i loro valori nel formato:

 ID: {id}, Name: {name}, Salary: {salary}

Provalo tu

#include <stdio.h>
#include <string.h>

int main() {
    // Scrivi il codice qui
    return 0;
};

Tutte le lezioni di Strutture in C/C++

Esercitati da solo: Compilatore C online