0

It seems like the following should copy t1 into t3 (that seems to be what the documentation I have read suggests)

#include<stdio.h>

struct test { 
  int a;
  char* name;
  struct test* b;
};


struct test t1, t2 = {.name = "foo", .a = 5, .b = &t2}, t3;

t3 = t1;

But this gives the error:

test.c:12:1: error: type specifier missing, defaults to 'int' [-Werror,-Wimplicit-int] 
t3 = t1;
^
test.c:12:1: error: redefinition of 't3' with a different type: 'int'  vs 'struct test'
test.c:10:57: note: previous definition is here
struct test t1, t2 = {.name = "foo", .a = 5, .b = &t2}, t3;
0

Try that assignment again in a function. I'd assume that you can only have initialisation, but not regular assignment outside of functions, and that's why the assignment is interpreted as an initialisation for a variable of undeclared type.

0

@BLauelf is correct, but this raises another question ... Why can't variables be assigned outside of a function?

I might want two copies of some complicated variable and

 my_type t1, t2 = "some long instantiation";
 t1 = t2;

feels like a reasonable thing to do. This fails simply because I am trying to redefine t1. The following would work:

 my_type t1, t2 = "some long instantiation";

 void copy(void) {
     t1 = t2;
 }

 // Now t1 is what I wanted in the first place?

Why does C not accept modifying variables outside of a function? The following won't compile:

int a;
a = 2;

While the following will:

int a; // defaults to 0

void change_a(int x) {
    a = x;
}

int main(void) {
    printf("a = %i\n", a); // Results in "a = 0"
    change_a(2);
    printf("a = %i\n", a); // Results in "a = 2"
}
2
  • Not exactly a good idea to write additions as an answer, maybe you should have added that to your original question, or created a new question. I haven't checked, but would assume my_type t2 = "some long instantiation", t1 = t2; to work, as it contains no assignment. I don't think there's a need for code outside functions, so there's no concept for that. – Blauelf Mar 3 '17 at 10:17
  • Thanks again, I wasn't sure where to add the new question. What you are saying is that this just doesn't come up ... except to those odd people who wonder what happens if ... (which is me). There must be a difference in the way variables, even global variables, work inside a function as opposed to outside a function, at least with respect to assignment. For some reason, after a variable in instantiated outside any function, it cannot be changed outside of a function. Thanks again for the answer and the advice. – ketchers Mar 3 '17 at 20:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .