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

typedef struct {
  char name[20];
  int favoriteNum;
} person;

int main(){

  person Gec = {"Gec", 1000};  //initialize var Gec of type struct person
  Foo = (person) {"Foo", 7};  //initialize var Foo of type struct person

  printf("%s's favorite number is %d.\n", Gec.name, Gec.favoriteNum);
  printf("%s's favorite number is %d.\n", Foo.name, Foo.favoriteNum);

  return 0;
}

Getting

"error: use of undeclared identifier 'Foo'".

Could it be that my version doesn't support using compound literals? Or am I doing something obviously wrong? Is the statement person Gec = {"Gec", 1000}; functionally the same as Gec = (person) {"Gec", 1000};? Saw this in a lab assignment but it wasn't explained in detail.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 4
    `Foo = (person) {"Foo", 7};` --> `person Foo = (person) {"Foo", 7};` There's no magical way the compiler is going to figure out the variable type, you have to supply it. – Sourav Ghosh Dec 08 '20 at 04:04
  • `Foo` still needs to be declared with a type. Unlike C++ and some other languages which do support such "magic", C won't infer the type of an object from the type of its initializer. – Nate Eldredge Dec 08 '20 at 04:09
  • There is good tutorial here about [compound literals](https://gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html) – IrAM Dec 08 '20 at 04:11
  • *"Saw this in a lab assignment but it wasn't explained in detail."* You need to find that, and add it to the question, because it didn't say what you seem to think it said. In some languages, types are inferred when an identifier is first used, and the type associated with an identifier can be changed. In C, you must explicitly specify the type for each and every identifier when declaring the identifier, and that type cannot be changed. – user3386109 Dec 08 '20 at 04:19
  • Does this answer your question? [What is an 'undeclared identifier' error and how do I fix it?](https://stackoverflow.com/questions/22197030/what-is-an-undeclared-identifier-error-and-how-do-i-fix-it) – Krishna Kanth Yenumula Dec 08 '20 at 04:28

1 Answers1

2

The following statement is assigning the value of a compound literal of type person to a variable named Foo:

Foo = (person) {"Foo", 7};

Unfortunately, in your program, there is no declaration for Foo yet when this statement is encountered by the compiler. Since this is a language violation, compilation fails.

There are various ways to fix this. However, if your intention is to observe the compound literal assignment working, and not initialization (which is already illustrated with Gec), then you can simply add a declaration for Foo above the assignment.

person Foo;
Foo = (person) {"Foo", 7};
jxh
  • 69,070
  • 8
  • 110
  • 193