I have a question about structs | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

I have a question about structs

What is the output of this code? struct A{ int a; float b; }; struct B{ int b; float a; }; struct C{ A a; B b; }; int main() { C c1={1,2,3,4}; C c2={5,6,7,8}; cout<<c1.b.a+c2.a.b; //Can you tell me this question with reasons? }

10th Oct 2017, 6:39 AM
Yusuf
Yusuf - avatar
2 Answers
+ 14
#include<iostream> using namespace std; struct A { int a; float b; }; struct B { int b; float a; }; struct C { A a; B b; }; int main () { // c1 is an instance of C struct. // Inside C struct 2 instances are created. // One of type A called a and another of // type B called b. // Type(struct) A and B, each has two variables. // One int and another float. // // As a result, you've got to initialize those ints and floats // in order to use each instances . // In fact, the corrected version is like this C c1 = {1, 2.0f, 3, 4.0f}; // {c1.a.a, c1.a.b, c1.b.b, c1.b.a} C c2 = {5, 6.0f, 7, 8.0f}; // {c2.a.a, c2.a.b, c2.b.b, c2.b.a} cout << c1.b.a + c2.a.b; // 4.0f + 6.0f = 10.0f //Can you tell me this question with reasons? }
10th Oct 2017, 7:34 AM
Babak
Babak - avatar
+ 2
Wow, good answer👍, by the way inserting this "//Can you tell me this question with reasons" into your answer better than your answer. @Babak
10th Oct 2017, 8:23 AM
Yusuf
Yusuf - avatar