Будет ли это работать или мне нужно объявить struct num вне main?
Ну, а почему бы просто не попробовать?
http://ideone.com дает:
Compilation error #stdin compilation error #stdout 0s 9424KB
prog.c: In function ‘main’:
prog.c:11:15: error: type of formal parameter 1 is incomplete
d = print_a(c);
^
prog.c:11:3: error: invalid use of undefined type ‘struct num’
d = print_a(c);
^
prog.c:10:14: warning: variable ‘d’ set but not used [-Wunused-but-set-variable]
struct num d;
^
prog.c: At top level:
prog.c:14:31: error: parameter 1 (‘c’) has incomplete type
struct num print_a(struct num c){
^
prog.c:14:12: error: return type is an incomplete type
struct num print_a(struct num c){
^~~~~~~
prog.c:14:12: error: conflicting types for ‘print_a’
prog.c:3:12: note: previous declaration of ‘print_a’ was here
struct num print_a(struct num c);
^~~~~~~
prog.c: In function ‘print_a’:
prog.c:16:10: warning: ‘return’ with a value, in function returning void
return c;
^
prog.c:14:12: note: declared here
struct num print_a(struct num c){
^~~~~~~
http://coliru.stacked -crooked.com / дает:
main.cpp: In function 'main':
main.cpp:13:15: error: type of formal parameter 1 is incomplete
d = print_a(c);
^
main.cpp:13:7: error: invalid use of undefined type 'struct num'
d = print_a(c);
^~~~~~~
main.cpp:12:14: warning: variable 'd' set but not used [-Wunused-but-set-variable]
struct num d;
^
main.cpp: At top level:
main.cpp:16:31: error: parameter 1 ('c') has incomplete type
struct num print_a(struct num c){
~~~~~~~~~~~^
main.cpp:16:12: error: return type is an incomplete type
struct num print_a(struct num c){
^~~~~~~
main.cpp:16:12: error: conflicting types for 'print_a'
main.cpp:5:12: note: previous declaration of 'print_a' was here
struct num print_a(struct num c);
^~~~~~~
main.cpp: In function 'print_a':
main.cpp:18:10: warning: 'return' with a value, in function returning void
return c;
^
main.cpp:16:12: note: declared here
struct num print_a(struct num c){
^~~~~~~
Хммм ... отчасти дают нам ответ: нет - это не будет работать
Когда вы определяете структуру внутри main, она известна только внутри main.Если вы хотите использовать структуру вне main, вы должны переместить определение структуры из main - например:
struct num {
int a;
int b;
};
struct num print_a(struct num c);
int main(){
struct num c = {1, 2};
struct num d;
d = print_a(c);
}
struct num print_a(struct num c){
printf("%d", c.a);
return c;
}