Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,161,567 members, 7,847,363 topics. Date: Saturday, 01 June 2024 at 04:16 PM

Simple C-codes That Still Confuse Me - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Simple C-codes That Still Confuse Me (1868 Views)

How To Run C# Codes Without Having To Install Visual Studio / What Softwares Are Used To Push Codes To A Live Website / Special Codes To Format Text On Nairaland (2) (3) (4)

(1) (Reply) (Go Down)

Simple C-codes That Still Confuse Me by Nobody: 5:55pm On Mar 25, 2015
//swaps two atomic variables of any type

int a = 10, b = 20;

a ^= b;
b ^= a;
a ^= b;

/*when the two variables are printed, they are automatically swapped */


please how does this work? smiley
Re: Simple C-codes That Still Confuse Me by Nobody: 6:50pm On Mar 25, 2015
geeks are not smiling.

how about this easier one.

//swaps a and b int variables.
void swap( int *a, int *b){
*a += (*b);
*b = (*a) - (*b);
*a = (*a) - (*b);
}


//yet another magic
Re: Simple C-codes That Still Confuse Me by Nobody: 6:57pm On Mar 25, 2015
//many ways to kill a rat

void swap(int *a, int *b){
a ^= b;
b ^= a;
a ^= b;

}
Re: Simple C-codes That Still Confuse Me by Nobody: 7:00pm On Mar 25, 2015
//nullify an uninitialized int


int a;
a ^= a;

//pew zero lurking behind a
Re: Simple C-codes That Still Confuse Me by WhiZTiM(m): 2:43pm On Mar 26, 2015
crotonite:
//swaps two atomic variables of any type

int a = 10, b = 20;

a ^= b;
b ^= a;
a ^= b;

/*when the two variables are printed, they are automatically swapped */


please how does this work? smiley

I assume you know a bit of binary numbers. And that "^" is a binary xor operator. And "^=" is the same, but accumulatin

Consider a 4bit integer.

int x = 2; //in binary, x = 0010;
int y = 5; //in binary, y = 0101;

Here's a truth table for xor operations.
0 xor 0 = 0
0 xor 1 = 1
1 xor 0 = 1
1 xor 1 = 0

...so
Lets see...
x ^= y;
x = x ^ y;
x = 0010 ^ 0101;
x = 0111;

y ^= x;
y = y ^ x;
y = 0101 ^ 0111;
y = 0010;

x ^= y;
x = x ^ y;
x = 0111 ^ 0010;
x = 0101;

....understood??
Re: Simple C-codes That Still Confuse Me by Nobody: 1:04pm On Mar 27, 2015
WhiZTiM:


I assume you know a bit of binary numbers. And that "^" is a binary xor operator. And "^=" is the same, but accumulatin

Consider a 4bit integer.

int x = 2; //in binary, x = 0010;
int y = 5; //in binary, y = 0101;

Here's a truth table for xor operations.
0 xor 0 = 0
0 xor 1 = 1
1 xor 0 = 1
1 xor 1 = 0

...so
Lets see...
x ^= y;
x = x ^ y;
x = 0010 ^ 0101;
x = 0111;

y ^= x;
y = y ^ x;
y = 0101 ^ 0111;
y = 0010;

x ^= y;
x = x ^ y;
x = 0111 ^ 0010;
x = 0101;

....understood??
pls can u teach me programming on "c" and if possible "matlab"
Re: Simple C-codes That Still Confuse Me by Nobody: 6:26pm On Mar 27, 2015
Mehn, see all this careting (not karating o) ehn? Na wa o, programming life is just too tough - what with carets, hashbangs and all that. . . . .
Re: Simple C-codes That Still Confuse Me by Nobody: 9:05pm On Mar 27, 2015
WhiZTiM:


I assume you know a bit of binary numbers. And that "^" is a binary xor operator. And "^=" is the same, but accumulatin

Consider a 4bit integer.

int x = 2; //in binary, x = 0010;
int y = 5; //in binary, y = 0101;

Here's a truth table for xor operations.
0 xor 0 = 0
0 xor 1 = 1
1 xor 0 = 1
1 xor 1 = 0

...so
Lets see...
x ^= y;
x = x ^ y;
x = 0010 ^ 0101;
x = 0111;

y ^= x;
y = y ^ x;
y = 0101 ^ 0111;
y = 0010;

x ^= y;
x = x ^ y;
x = 0111 ^ 0010;
x = 0101;

....understood??

thanks and capital yes.
Re: Simple C-codes That Still Confuse Me by Nobody: 9:20pm On Mar 27, 2015
//how about passing a 2d array to a function?


//for 1d array array 1 could simply write

void take1DArr( int arr[], int len]{

int i; //do array indexing with var i

while(i < (len-1))

{ //do something magical with array arr[]

}
}//end of func.




//a buggy function that accepts 2d array

void take2DArr( int arr[][]){

// this doesn't compile whatz wrong

}



how is the right way to pass a 2d array to a funtion?
Re: Simple C-codes That Still Confuse Me by Nobody: 9:26pm On Mar 27, 2015
dhtml18:
Mehn, see all this careting (not karating o) ehn? Na wa o, programming life is just too tough - what with carets, hashbangs and all that. . . . .


they are the slangs the preprocessors love listening to/ lol
Re: Simple C-codes That Still Confuse Me by Nobody: 5:16am On Mar 28, 2015
^^^^Yes o, and programmers must keep talking in these slangs on a daily basis. No wonder the outside world call us NERDS!
Re: Simple C-codes That Still Confuse Me by codemarshal08(m): 6:25am On Mar 28, 2015
crotonite:
//how about passing a 2d array to a function?


//for 1d array array 1 could simply write

void take1DArr( int arr[], int len]{

int i; //do array indexing with var i

while(i < (len-1))

{ //do something magical with array arr[]

}
}//end of func.




//a buggy function that accepts 2d array

void take2DArr( int arr[][]){

// this doesn't compile whatz wrong

}



how is the right way to pass a 2d array to a funtion?

if you work with c++ then you must supply at least the Number of columns when passing a multi-dimensional array to a function. So your options are , either supply both sizes OR only supply the size of the columns

so your code should be like this :
const int cols = 6:
void take2DArr( int arr[][cols]){

// do your array processing here !

}

note: dhtml18, i sight you o. Greetings !
Re: Simple C-codes That Still Confuse Me by Nobody: 6:48am On Mar 28, 2015
codemarshal08:


if you work with c++ then you must supply at least the Number of columns when passing a multi-dimensional array to a function. So your options are , either supply both sizes OR only supply the size of the columns

so your code should be like this :
const int cols = 6:
void take2DArr( int arr[][cols]){

// do your array processing here !

}

note: dhtml18, i sight you o. Greetings !


but what i want is a very flexibly array like the 1d array that i can pass an array of any size of row or column. but it seems the above col is cons. isn't it?


by the way thanks so much
Re: Simple C-codes That Still Confuse Me by Nobody: 6:54am On Mar 28, 2015
dhtml18:
^^^^Yes o, and programmers must keep talking in these slangs on a daily basis. No wonder the outside world call us NERDS!

compared to geek which is more derogatory?




me prefer geek coz i love geeking. nerd!! that word makes me wanna throw-up.
Re: Simple C-codes That Still Confuse Me by codemarshal08(m): 7:31am On Mar 28, 2015
crotonite:



but what i want is a very flexibly array like the 1d array that i can pass an array of any size of row or column. but it seems the above col is cons. isn't it?


by the way thanks so much

hehe. i am sorry, in c++ you are not allowed to do such. Compiliers need to know at least how wide the column is. ANYWAY, you could go for a VECTOR . It is a good alternative !
Re: Simple C-codes That Still Confuse Me by Nobody: 10:33am On Mar 28, 2015
codemarshal08:


hehe. i am sorry, in c++ you are not allowed to do such. Compiliers need to know at least how wide the column is. ANYWAY, you could go for a VECTOR . It is a good alternative !


thanks bro!, i think your the best on nl. can i folow, folow you on nl ? smiley








more wisdoms to your bucket of wisdom
Re: Simple C-codes That Still Confuse Me by codemarshal08(m): 10:45am On Mar 28, 2015
crotonite:



thanks bro!, i think your the best on nl. can i folow, folow you on nl ? smiley








more wisdoms to your bucket of wisdom
you 're welcome bro. Sure you could. Remember: we all are here to share ideas !
Re: Simple C-codes That Still Confuse Me by ToyinDipo(m): 11:56am On Mar 28, 2015
crotonite:
geeks are not smiling.

how about this easier one.

//swaps a and b int variables.
void swap( int *a, int *b){
*a += (*b);
*b = (*a) - (*b);
*a = (*a) - (*b);
}


//yet another magic

Funny enough, I submitted this exact method as a solution to a pre-interview question requesting swap of two variables without third variable

1 Like

Re: Simple C-codes That Still Confuse Me by Nobody: 12:06pm On Mar 28, 2015
ToyinDipo:


Funny enough, I submitted this exact method as a solution to a pre-interview question requesting swap of two variables without third variable


did you test it before submitting? this works only with intergers

you know buggs are sometimes creepy and hard to spot.

peace.
Re: Simple C-codes That Still Confuse Me by ToyinDipo(m): 12:10pm On Mar 28, 2015
crotonite:



did you test it before submitting? this works only with intergers

you know buggs are sometimes creepy and hard to spot.

peace.



I didn't test. I only drafted it like an algorithm. I didn't even write in any programing language platform.

Is there any universal algorithm to achieve that, an algorithm that can handle all datatypes
Re: Simple C-codes That Still Confuse Me by Nobody: 12:24pm On Mar 28, 2015
ToyinDipo:




I didn't test. I only drafted it like an algorithm. I didn't even write in any programing language platform.

Is there any universal algorithm to achieve that, an algorithm that can handle all datatypes

universal? i guess no.
Re: Simple C-codes That Still Confuse Me by WhiZTiM(m): 3:03pm On Mar 28, 2015
crotonite:
//how about passing a 2d array to a function?

void take2DArr( int arr[][]){

// this doesn't compile whatz wrong

}[/color]

how is the right way to pass a 2d array to a funtion?

Well, codemarsharl08 is right. But just to expand more,

The size of C++ arrays must be known at compile time. (except for heap allocated arrays);
For every function you call, the CPU must do two things:

1. fetch the address of the function (just like a variable)
2. fetch the function's stack size; (think of it like a block of memory which represents your entire function)


There are of cause different ways the compiler may transform function arguments, but the point here is that, once you compile your program, a function's stack size NEVER changes. (Mainly because of caching -> hence insane execution speed in tight loops). ..and of cause Inlining

When compiling, the compiler must resolve the sizes of all functions, including the arguments;
When you pass a 1D array,

void take1DArray(int arr[]);
//the compiler transforms the above call to:
void take1DArray(int* arr);



This is because, for any expression, an array is permitted to implicitly decompose ONLY once!.
Array decomposition is basically the transformation of an array to a pointer;

The syntax "typename Type[]" is a declaration of a variable length array and is exactly the same as "typename* Type".
Hence, "int arr[]" is same as "int* arr";

Do you know that whenever you declare an array like this,

{
int arr[] = {1, 2, 3, 4, 5};
//or
int arr[5] = {1, 2, 3, 4, 5};
}


Within its declaration scope( '{' and '}' ), "arr" still has a its 'size' property. Hence for that reason, "sizeof(arr)" will always give you the total size of the array;

When you pass "arr" to any function, that property implicitly disappears. Hence, "arr" is decomposed.
Example
void take1d(int arr[])
{
//blaa blah blah
sizeof(arr); ...gives you size of a pointer, same as sizeof(arr*)
}

void take1D(int arr[3])
{
//blaa blah blah
sizeof(arr); ...gives you size of a pointer, same as sizeof(arr*)
}

int main()
{
int arr[] = {1, 2, 3, 4, 5};
sizeof(arr); ...gives you the lump size of 5 ints
}




========Now, what about 2D arrays and above=========
Exactly the same thing applies!

You have 4 choices:

void take2D(int** arr, int sz1, int sz2);
void take2D(int* arr[], int sz1, int sz2);
void take2D(int arr[][5], int sz1, int sz2);
void take2D(int arr[5][5], int sz1, int sz2);


...they are all the same. just syntactic sugar; The last two will probably help only in bounds checking

...Now, back to our previous discussion on Function Size:
The Compiler must know the size of a function. But all array parameters in a function are implicitly pointers;

In any context, the compiler is only allowed to perform implicit operations once! ...whether, implicit conversions, construction, etc;...
In doing "int arr[][] ...", you are asking the compiler to perform implicit operations of decomposition or calculating more than once!... this breaks it's Automata and design principles. There may be other better reasons though.

========Etcetera=========
There are current efforts for function stacks to be variable at runtime.
This involves a lot of compiler intricacies, and machine-code injection by the C++ runtime;
Variable stack is the foundation to a new container that didn't make it into the C++11 and C++14 standards. --> std::dynarray;

The ISO C++ committee voted it out, partly because the proposed algorithm wasn't as fast as a native function call. And it required deep intricate support from compilers and its runtime. Though intensive efforts are being made to improve it and have it acceptable... Hopefully by C++1y, (C++17).

....whew... that was one hell of an explanation! ....(Well, I was a bit jobless, and felt I could write something... :-) )
Perharps, I should turn this comment into a new thread?

...regards,
Timothy
Re: Simple C-codes That Still Confuse Me by WhiZTiM(m): 3:31pm On Mar 28, 2015
SAVEDBABA:
pls can u teach me programming on "c" and if possible "matlab"
Well, I don't know how that will work, cause I think there are so many resources available online...
...Not only I, but so many great people here can provide you with pointers... so, you are always welcome to ask... smiley
Re: Simple C-codes That Still Confuse Me by codemarshal08(m): 3:57pm On Mar 28, 2015
@WhiZTiM, dat was a whole lot of nice explanation ! Kudos....

1 Like

Re: Simple C-codes That Still Confuse Me by Nobody: 4:04pm On Mar 28, 2015
WhiZTiM:


Well, codemarsharl08 is right. But just to expand more,

The size of C++ arrays must be known at compile time. (except for heap allocated arrays);
For every function you call, the CPU must do two things:

1. fetch the address of the function (just like a variable)
2. fetch the function's stack size; (think of it like a block of memory which represents your entire function)


There are of cause different ways the compiler may transform function arguments, but the point here is that, once you compile your program, a function's stack size NEVER changes. (Mainly because of caching -> hence insane execution speed in tight loops). ..and of cause Inlining

When compiling, the compiler must resolve the sizes of all functions, including the arguments;
When you pass a 1D array,

void take1DArray(int arr[]);
//the compiler transforms the above call to:
void take1DArray(int* arr);



This is because, for any expression, an array is permitted to implicitly decompose ONLY once!.
Array decomposition is basically the transformation of an array to a pointer;

The syntax "typename Type[]" is a declaration of a variable length array and is exactly the same as "typename* Type".
Hence, "int arr[]" is same as "int* arr";

Do you know that whenever you declare an array like this,

{
int arr[] = {1, 2, 3, 4, 5};
//or
int arr[5] = {1, 2, 3, 4, 5};
}


Within its declaration scope( '{' and '}' ), "arr" still has a its 'size' property. Hence for that reason, "sizeof(arr)" will always give you the total size of the array;

When you pass "arr" to any function, that property implicitly disappears. Hence, "arr" is decomposed.
Example
void take1d(int arr[])
{
//blaa blah blah
sizeof(arr); ...gives you size of a pointer, same as sizeof(arr*)
}

void take1D(int arr[3])
{
//blaa blah blah
sizeof(arr); ...gives you size of a pointer, same as sizeof(arr*)
}

int main()
{
int arr[] = {1, 2, 3, 4, 5};
sizeof(arr); ...gives you the lump size of 5 ints
}




========Now, what about 2D arrays and above=========
Exactly the same thing applies!

You have 4 choices:

void take2D(int** arr, int sz1, int sz2);
void take2D(int* arr[], int sz1, int sz2);
void take2D(int arr[][5], int sz1, int sz2);
void take2D(int arr[5][5], int sz1, int sz2);


...they are all the same. just syntactic sugar; The last two will probably help only in bounds checking

...Now, back to our previous discussion on Function Size:
The Compiler must know the size of a function. But all array parameters in a function are implicitly pointers;

In any context, the compiler is only allowed to perform implicit operations once! ...whether, implicit conversions, construction, etc;...
In doing "int arr[][] ...", you are asking the compiler to perform implicit operations of decomposition or calculating more than once!... this breaks it's Automata and design principles. There may be other better reasons though.

========Etcetera=========
There are current efforts for function stacks to be variable at runtime.
This involves a lot of compiler intricacies, and machine-code injection by the C++ runtime;
Variable stack is the foundation to a new container that didn't make it into the C++11 and C++14 standards. --> std::dynarray;

The ISO C++ committee voted it out, partly because the proposed algorithm wasn't as fast as a native function call. And it required deep intricate support from compilers and its runtime. Though intensive efforts are being made to improve it and have it acceptable... Hopefully by C++1y, (C++17).

....whew... that was one hell of an explanation! ....(Well, I was a bit jobless, and felt I could write something... :-) )
Perharps, I should turn this comment into a new thread?

...regards,
Timothy



thank you man. are you a proffessor or what?
anyway i have never come across such a superb explanation of array and pointers before. wow so easy to understand.






pls can you explain for me stacks and function calls when your chanced?
Re: Simple C-codes That Still Confuse Me by Nobody: 9:23am On Mar 29, 2015
WhiZTiM:


Well, codemarsharl08 is right. But just to expand more,

The size of C++ arrays must be known at compile time. (except for heap allocated arrays);
For every function you call, the CPU must do two things:

1. fetch the address of the function (just like a variable)
2. fetch the function's stack size; (think of it like a block of memory which represents your entire function)


There are of cause different ways the compiler may transform function arguments, but the point here is that, once you compile your program, a function's stack size NEVER changes. (Mainly because of caching -> hence insane execution speed in tight loops). ..and of cause Inlining

When compiling, the compiler must resolve the sizes of all functions, including the arguments;
When you pass a 1D array,

void take1DArray(int arr[]);
//the compiler transforms the above call to:
void take1DArray(int* arr);



This is because, for any expression, an array is permitted to implicitly decompose ONLY once!.
Array decomposition is basically the transformation of an array to a pointer;

The syntax "typename Type[]" is a declaration of a variable length array and is exactly the same as "typename* Type".
Hence, "int arr[]" is same as "int* arr";

Do you know that whenever you declare an array like this,

{
int arr[] = {1, 2, 3, 4, 5};
//or
int arr[5] = {1, 2, 3, 4, 5};
}


Within its declaration scope( '{' and '}' ), "arr" still has a its 'size' property. Hence for that reason, "sizeof(arr)" will always give you the total size of the array;

When you pass "arr" to any function, that property implicitly disappears. Hence, "arr" is decomposed.
Example
void take1d(int arr[])
{
//blaa blah blah
sizeof(arr); ...gives you size of a pointer, same as sizeof(arr*)
}

void take1D(int arr[3])
{
//blaa blah blah
sizeof(arr); ...gives you size of a pointer, same as sizeof(arr*)
}

int main()
{
int arr[] = {1, 2, 3, 4, 5};
sizeof(arr); ...gives you the lump size of 5 ints
}




========Now, what about 2D arrays and above=========
Exactly the same thing applies!

You have 4 choices:

void take2D(int** arr, int sz1, int sz2);
void take2D(int* arr[], int sz1, int sz2);
void take2D(int arr[][5], int sz1, int sz2);
void take2D(int arr[5][5], int sz1, int sz2);


...they are all the same. just syntactic sugar; The last two will probably help only in bounds checking

...Now, back to our previous discussion on Function Size:
The Compiler must know the size of a function. But all array parameters in a function are implicitly pointers;

In any context, the compiler is only allowed to perform implicit operations once! ...whether, implicit conversions, construction, etc;...
In doing "int arr[][] ...", you are asking the compiler to perform implicit operations of decomposition or calculating more than once!... this breaks it's Automata and design principles. There may be other better reasons though.

========Etcetera=========
There are current efforts for function stacks to be variable at runtime.
This involves a lot of compiler intricacies, and machine-code injection by the C++ runtime;
Variable stack is the foundation to a new container that didn't make it into the C++11 and C++14 standards. --> std::dynarray;

The ISO C++ committee voted it out, partly because the proposed algorithm wasn't as fast as a native function call. And it required deep intricate support from compilers and its runtime. Though intensive efforts are being made to improve it and have it acceptable... Hopefully by C++1y, (C++17).

....whew... that was one hell of an explanation! ....(Well, I was a bit jobless, and felt I could write something... :-) )
Perharps, I should turn this comment into a new thread?

...regards,
Timothy


I have an advice/request for you, I know this seems nonsensical but there is always a sense in every nonsense.
the way you explained the above topic shows that you have something special that I have not come across for a long while. please would you mind if I name you the 'king-of-abstractions' on nl?
let me get to the point, would you mind putting down some tutorials or if possible a textbook for nigerian aspiring coders? something like the 'for dummies serries'. but I think it can be called 'coding for akpos!' it could be of any lenght but with time it can be improved. bros you can touch so many lifes I tell you.

Thank you and God bless.
Re: Simple C-codes That Still Confuse Me by Nobody: 9:35am On Mar 29, 2015
crotonite:


compared to geek which is more derogatory?




me prefer geek coz i love geeking. nerd!! that word makes me wanna throw-up.
I am not a geek, I AM GREEK! I remember that article.
Re: Simple C-codes That Still Confuse Me by Nobody: 2:38pm On Mar 29, 2015
dhtml18:

I am not a geek, I AM GREEK! I remember that article.
GREEK, I never read that article.
you know I am still a newbie on nl. maybe when the article was published, I was still under the rock!!
Re: Simple C-codes That Still Confuse Me by WhiZTiM(m): 11:12am On Apr 02, 2015
crotonite:

thank you man. are you a proffessor or what?
anyway i have never come across such a superb explanation of array and pointers before. wow so easy to understand.
pls can you explain for me stacks and function calls when your chanced?
You are very much welcome.
Nope, I am not a Professor (at least, not yet). :-)
I am just a Systems guy...

crotonite:

anyway i have never come across such a superb explanation of array and pointers before. wow so easy to understand.
pls can you explain for me stacks and function calls when your chanced?
Sure... I will.
EDIT: I have.. please see: https://www.nairaland.com/2232875/simple-explanation-functions-stacks

crotonite:

I have an advice/request for you, I know this seems nonsensical but there is always a sense in every nonsense.
the way you explained the above topic shows that you have something special that I have not come across for a long while. please would you mind if I name you the 'king-of-abstractions' on nl?
...hehe... It's not nonesense. ... But How can I be King of Abstractions when there is no kingdom? smiley ...that will be akin to King Julien in "Penguins of Madagascar" ...lolz

crotonite:

let me get to the point, would you mind putting down some tutorials or if possible a textbook for nigerian aspiring coders? something like the 'for dummies serries'. but I think it can be called 'coding for akpos!' it could be of any lenght but with time it can be improved. bros you can touch so many lifes I tell you.
Thank you and God bless.
Well, Thanks for the suggestion.

(1) (Reply)

What You Need To Know Before Developing A Website Or Mobile App / How To Design An Antivirus Software Using Virus Signature Defination / In Need Of Freedom Configuration Settings

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 81
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.