c - Making function behave like a scope -


i'm working on project becoming more , more complicated. project consists of independent each other sections of code containing lot of math computations followed complicated output generation. wrapped inside socket pthread.

whole thing looks this:

main() -> socket -> thread -> request processing -> 1 or more of independent sections

i wanted enclose each independent section of code inside function, , function inherit variables caller function, didn't work.

below simplified version of want achieve:

void func_a(){int c;b+=a;c=1;b+=c;} int main(){  int a,b,c;  a=3;b=2;c=0;  func_a();  printf("b:%d c:%d\n",b,c);  return 1; } 

above code doesn't work, 1 works fine, , want:

int main(){  int a,b,c;  a=3;b=2;c=0;  {int c;b+=a;c=1;b+=c;}  printf("b:%d c:%d\n",b,c);  return 1; } 

i put code function file, , { #include ... }, perhaps there's better way that?

any other ideas , suggestions on managing such thing appreciated too.

thanks.

p.s.

using global scope not option, because of threading. passing variables function not option, take 30+ arguments. have bunch of struct's going on, putting variables single struct not option ether.

there different ways achieve need.

the first use gcc nested functions. unfortunately, nonstandard, , such entirely compiler-dependent. can find information here : stack overflow nested c function , on gcc nested functions manual. if don't need portability may valid solution.

another solution may define macro code of pseudo function. compiler substitute every times macros called , automatically inheritances variable defined caller function.

i rewrote example both solutions.

#include <stdio.h>  #define func_a()  {int c;b+=a;c=1;b+=c;}  #define func_a2(_a,_b) {int c;_b+=_a;c=1;_b+=c;}   int main(){    int a,b,c;    void func_a(){int c;b+=a;c=1;b+=c;}     // nested solution     a=3;b=2;c=0;     func_a();     printf("b:%d c:%d\n",b,c);      // macro solution     a=3;b=2;c=0;      func_a();      printf("b:%d c:%d\n",b,c);      // macro solution     a=3;b=2;c=0;      func_a2(a,b);     printf("b:%d c:%d\n",b,c);      return 0; } 

all solutions have same result. :d


Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -