Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

[SOLVED] IF statement and STRUCT

Status
Not open for further replies.

hanshen

Junior Member level 1
Joined
Oct 31, 2010
Messages
18
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,409

Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
 
#define INIT_SUM(a,b,c)                                     \
struct test _test_struct = {(a),(b),(c)};
 
typedef void (*sum)(unsigned char a, unsigned char b);
 
struct test{
    unsigned char x;
    unsigned char y;
    
    sum ptr_sum;
};
void summing(unsigned char w, unsigned char e);
 
int main(){
    INIT_SUM(0,0,summing)   
    if(_test_struct.ptr_sum)
        _test_struct.ptr_sum(6,8);
    while(!getchar());
}
 
void summing(unsigned char w,unsigned char e){
    printf("answer is %d",w+e);
}



In the statment "if(_test_struct.ptr_sum)", why the IF statement is true for the statement " _test_struct.ptr_sum(6,8);" is executed?
 

What do you want to learn from this example? Writing mysterious C code?
 

if(_test_struct.ptr_sum) //if the functionpointer is assigned (aka not zero)
_test_struct.ptr_sum(6,8); //call the function with 6,8

And the ansver is 14 .. And sadly not 42 - stupid example

/Bingo
 

Sorry i did not state the question clearly. Actually i saw the part "if(_test_struct.ptr_sum)" in others people code. I try to implement it by making some modification. The main point is that i don't understand why a void function in IF statement's expression will allow the execution of IF statement. Since from what i known, the void function do not return any value, thus the condition for the execution of IF statement will not occur. However from the code, the IF statement executed.
 

You have to read the code bottom-up and line by line.

This is a function pointer definition
Code:
typedef void (*sum)(unsigned char a, unsigned char b);

Thus ptr_sum is a function pointer.

if(_test_struct.ptr_sum) checks if the pointer is defined before calling the function.

Just plain C code ...
 
Thanks, I never thought about that. I appreciate it very much, thanks again.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top